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…?
Views don’t have an
onDestroymethod 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 theonDestroy, i.e:So the GC can do its job. I had the same problem with the
AdViewof AdMob, although they did have adestroymethod it didn’t really help. But deleting my references of the view fixed the problem.