聆听“Google I/O 2012 - 用更少的资源做更多的事:做一个好的 Android 公民”演讲,您可以在这里看到 http://www.youtube.com/watch?v=gbQb1PVjfqM&list=PL4C6BCDE45E05F49E&index=10&feature=plpp_video我发现自 api 级别 14 起,如果您想做一些事情(例如减少内存使用),您可以覆盖 onTrimMemory
。但是我想在我的 Activity 之外实现 ComponentCallbacks2 接口(interface),例如在我的 CursorAdapter 中。在这个演讲中它说:使用 Context.registerComponentCallbacks()
,但是当我尝试使用它时它需要一个输入参数,就像这样 mContext.registerComponentCallbacks(ComponentCallbacks callbacks);
我该如何使用它?
我现在正在用这个
public class ContactItemAdapter extends ResourceCursorAdapter implements ComponentCallbacks2{
... ...
@Override
public void onTrimMemory(int level) {
Log.v(TAG, "onTrimMemory() with level=" + level);
// Memory we can release here will help overall system performance, and
// make us a smaller target as the system looks for memory
if (level >= TRIM_MEMORY_MODERATE) { // 60
// Nearing middle of list of cached background apps; evict our
// entire thumbnail cache
Log.v(TAG, "evicting entire thumbnail cache");
mCache.evictAll();
} else if (level >= TRIM_MEMORY_BACKGROUND) { // 40
// Entering list of cached background apps; evict oldest half of our
// thumbnail cache
Log.v(TAG, "evicting oldest half of thumbnail cache");
mCache.trimToSize(mCache.size() / 2);
}
}
}
但是 onTrimMemory
永远不会被调用。
最佳答案
由于您的 Adapter 类已经实现了 ComponentCallbacks2,您应该能够将 Adapter 实例作为参数传递给 registerComponentCallbacks()
。
从您的 Activity 来看,这样的事情应该有效:
registerComponentCallbacks( mAdapter );
之后,您应该收到 onTrimMemory()
回调。
关于android onTrimMemory 和 ComponentCallbacks2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12710672/