【问题标题】:Clear image resource from memory after nullifying无效后从内存中清除图像资源
【发布时间】:2017-06-07 13:58:20
【问题描述】:

我有一个 Android Activity 需要在应用程序的整个生命周期内保存在内存中(不要问为什么)。这个Activity的后台占用了大约12MB的内存。我想在未查看此活动时释放此内存空间。我尝试添加以下代码

@Override
protected void onPause() {
    setBackground(null);
    super.onPause();
}


@Override
protected void onResume() {
    super.onResume();
    setBackgroundResource(R.drawable.bg);
}

但这会导致内存空间仍然被分配。下面的树是通过 MAT 检索到的,如您所见,没有直接引用我的应用程序本身。

我怀疑位图在内存中的某个地方,等待 gc'd,但无论出于何种原因,它永远不会。

仅供参考,我也尝试了以下方法

private Drawable background;

@Override
protected void onResume() {
    background = activity.getResources().getDrawable(R.drawable.bg);
    setBackground(background);
}

@Override
protected void onPause() {
    setBackground(null);
    background = null;
}

但这导致了这种疯狂

【问题讨论】:

    标签: java memory-leaks android-memory hprof eclipse-mat


    【解决方案1】:

    原来是打电话

    ((BitmapDrawable)background).getBitmap().recycle();
    

    从内存中清除数据,而清空对象则不会!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-29
      相关资源
      最近更新 更多