android onTrimMemory和ComponentCallbacks2

San*_*dra 1 memory android callback

聆听"谷歌I/O 2012 - 少花钱多办事:成为优秀的Android公民"讲座,你可以在这里看到http://www.youtube.com/watch?v=gbQb1PVjfqM&list=PL4C6BCDE45E05F49E&index=10&feature=plpp_video i发现自从api 14级以来你可以覆盖,onTrimMemory如果你喜欢做一些事情,比如减少内存使用量.但是我想在我的Activity中,在我的CursorAdapter中实现ComponentCallbacks2接口.在这个讲话中它说:use 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

onTrimMemory永远不会被召唤.

acj*_*acj 8

由于您的Adapter类已经实现了ComponentCallbacks2,您应该能够将Adapter实例作为参数传递给registerComponentCallbacks().

根据您的活动,这样的事情应该有效:

registerComponentCallbacks( mAdapter );
Run Code Online (Sandbox Code Playgroud)

之后,您应该收到onTrimMemory()回调.