安卓:在应用程序清理内存破坏 [英] android: cleaning up memory on app destroy
问题描述
我在开发的实例一堆位图对象的应用程序(例如按键,其中有位图缓存,所以他们没有得到再次呈现,再)
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)
现在,我意识到,当我在我的华为移动设备上重复运行,并启动应用程序,我在那里的应用程序尝试分配一些内存为位图的一个点得到一个OutOfMemoryException。
所以我想这是其闹事的位图。我知道有一个bitmap.recycle()方法,虽然。
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.
现在我的问题:什么是清理内存的最佳实践?
为什么没有像查看::的onDestroy(),它可以用于清理目的而实施了一些方法查看?
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?
编辑:例如
我的CirclyButton(扩展了Button)班总是拿缓存的位图的onDraw:
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...?
推荐答案
视图不具有的onDestroy
方法,因为意见通常不被摧毁,活动做。视图将没有任何反应其活动不只是被破坏(除非你抬高不同的布局......这是不是这样的,对吧?),如果事情发生在它的活动中,你有一个回调得到调用。
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.
如果有一个循环()
方法,请确保你怎么称呼它。并删除的所有的参考内存取物品在的onDestroy
,即:
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;
//...
}
所以GC可以做自己的工作。我与的AdView的AdMob
,虽然他们也有一个摧毁
方法,它并没有真正帮助了同样的问题。但我删除视图的引用解决了这一问题。
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.
这篇关于安卓:在应用程序清理内存破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!