android: cleaning up memory on app destroy

2019-08-01 15:07发布

I am developing an app which instantiates a bunch of bitmap objects (e.g. buttons, which have cache bitmaps, so they don't have to get rendered again and again)

Now, I realised that when I run and start the app repeatedly on my huawei mobile device, I get an OutOfMemoryException at a point where the app tries to allocate some memory for the bitmaps. So I guess it's the bitmaps which make trouble. I do know that there is a bitmap.recycle() method though.

Now my question: what is best practice to clean up memory? Why isn't there some View method like View::onDestroy() which can be implemented for cleanup purpose?

EDIT: example

my "CirclyButton" (extends Button) class always draws a cached bitmap onDraw:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(this.getDefaultBitmap(), 0, 0, paint);
    }
    private Bitmap getDefaultBitmap(){
        if(mBitmapDefault == null){
            mBitmapDefault = Bitmap.createBitmap(8*radius, 8*radius, Config.ARGB_8888);
            Canvas canvas = new Canvas(mBitmapDefault);
            this.drawDefault(canvas);
            return mBitmapDefault;
        }
        return mBitmapDefault;
    }

So I guess this allocated data should be recycled somewhere...?

2条回答
相关推荐>>
2楼-- · 2019-08-01 15:38

Provide more information about where are you using your bitmaps, i have some serious experience of working with images and saving memory.

For example in my app i have a list of some data, which display some bitmap in each row. I store my list in a fragment(for fragment support i use compatibility library), and i recycled my bitmaps on this fragment onDestroy method.

Later i decided to optimize my list, so i added scroll listener to my list and started recycling bitmaps, when they are scrolled off the screen.

查看更多
手持菜刀,她持情操
3楼-- · 2019-08-01 16:01

Views don't have an onDestroy method because views usually don't get destroyed, activities do. A view won't just be destroyed if nothing happens to its activity (Unless you inflate a different layout... That's not the case, right?), and if something happens to its activity, you do have a callback getting called.

If there is a recycle() method, make sure you call it. And remove all reference to memory taking objects in the onDestroy, i.e:

@Override
public void onDestroy() {
    object1 = null;
    object2 = null;
    //...
}

So the GC can do its job. I had the same problem with the AdView of AdMob, although they did have a destroy method it didn't really help. But deleting my references of the view fixed the problem.

查看更多
登录 后发表回答