android onTrimMemory 和 ComponentCallbacks2

标签 android memory callback

聆听“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/

相关文章:

javascript - React Native 是否将 JavaScript 编译为 Android 的 Java?

android - 按钮如何获得焦点在android中点击

android - 您是否应该中止所有正在运行的线程和 Activity 的 onDestroy()

WPF-应用程序内存泄漏

javascript - 您存储返回回调的回调的模式是否有名称?

android - 使用 Android Camera 进行图像处理

memory - 黑莓上的堆栈大小?

memory - Quartus 初始化 RAM

php - 在 PHP 中传递带有参数的回调

android - 模块间通信的最佳实践