How to make sure Android bitmaps are cleared out of Heap

非 Y 不嫁゛ 提交于 2019-12-08 06:46:11

问题


I have an activity (activity1) which uses a decently large amount of bitmaps. I also have another activity which loads bitmaps (activity2). When running on some phones, I get an OOM error in activity2. I've tracked down the error to being caused by the layout in activity1. If I take out all of the bitamps in activity1, and replace them with just hex colors, then I do not get an OOM error in activity2.

So from this I'm assuming that the bitmaps I'm using in activity1 are not being removed from the heap when activity1's onPause or onDestroy methods are called. So far I've tried the answer from here but I still get my OOM error. Here's my onPause and onResume methods so far.

@Override
protected void onPause() {
    mCache.onPause();
    mContext = null;

    mTimer.cancel();
    mTimer = null;

    unbindDrawables(findViewById(R.id.home_root));
    System.gc();

    super.onPause();
}

private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
    view.getBackground().setCallback(null);
    }
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
    ((ViewGroup) view).removeAllViews();
    }
}

@Override
protected void onResume() {
    super.onResume();
    setContentView(R.layout.homescreen);
    createButtons();
    mCache.onResume();
    performAnimation(false);

    mTimer = new Countdown();
    mTimer.start();
}

Any suggestions on how to fix this would be greatly appreciated! Thanks.


回答1:


You could use the bitmap.recycle() method for all bitmaps loaded in memory, as long as you make sure you load them later again when you use them.

According to documentation, the recycle() method should not be used as it is considered bad practice to attempt to manage memory manually in Java. However, if you use this in conjunction with the System.gc() call I see in your onPause(), you could theoretically speed up the GC process for your problematic phones by explicitly stating unneeded bitmaps.

I don't see any Bitmap code in your snippet, maybe a bit more information could help clarify your problem.



来源:https://stackoverflow.com/questions/11711165/how-to-make-sure-android-bitmaps-are-cleared-out-of-heap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!