Android的 - 内存泄漏还是? [英] Android - memory leak or?
问题描述
前两天我发现了一些。我有一个微调在地图的活动。在活动的OnCreate()方法,我用数据填充微调。从那以后,我开始在DDMS堆分析我开始打开/关闭微调。我注意到虚拟机分配内存,当我打开微调的项目,但是当我关闭它,虚拟机做不释放此内存。我试图启动GC,但内存仍分配。我这样做20次一个接一个,并从3.5MB分配的内存提高到7MB。哪里不对?我发现在谷歌小组的问题,但他们还没有回答。
微调内存泄漏
two days ago i noticed something. I have a spinner over a map activity. In the OnCreate() method of the activity i populate the spinner with data. After that i start the heap analyzer in DDMS i begin to open/close the spinner. I noticed the VM allocate memory when i open the spinner items, but when i close it, the VM do no free this memory. I've tried to start the GC, but the memory is still allocated. i did this 20 times one by one and the allocated memory increased from 3.5MB to 7MB. What is wrong? I found an issue in google groups, but they haven't answered yet.
Spinner memory leak
我重写我的所有code在微调适配器,但问题仍然存在。 我这个话题在读了一些意见
I rewrite all my code in the spinner adapter, but the issue still remains. I read some advices in this topic
也有一些是我没得到:
当绘制对象附加到一个视图,该视图被设置为在绘制回调。在上面的code段,这意味着绘制有一个参照其本身具有参考性(语境),这反过来引用了pretty的任何东西TextView的(取决于你的$ C $角)
这是什么意思?如果我有一个TextView,并将其设置的可绘制对象(我注意到的绘制是静态的),TextView的对象的引用,绘制对象和绘制对象的引用,看法吗?如果这是真的,它们成为undestroyable通过GC进行,因为它们都具有相互之间的引用?对象之间是什么反向引用(回调)dependencе?
What does it mean? If i have a textview and set it a drawable object (i noticed the drawable is static), the textview object has a reference to the drawable object and the drawable object has a reference to the view too? If this is true, they become undestroyable by the GC because they both have references to each other? What is this back-reference (callbacks) dependencе between the objects?
推荐答案
抱歉,我不能帮助你的微调问题,但我可以对第二部分一试:
Sorry I can't help you on your Spinner problem but I can have a try on the second part:
在Android开发者博客罗曼盖伊后解释两个重要的事情。
Romain Guy post on android developer blog explain two important things.
第一:
当你创建一个视图(TextView的,ImageView的......),你不得与活动场景创建
When you create a View (TextView, ImageView...) you must not create it with the activity Context
// DO NOT DO THIS
TextView label = new TextView(this);
否则观统领引用您的活动,将永远不会被释放。
Otherwise the View get a reference to your activity and will never be deallocated.
相反,当你编程方式创建一个视图,你必须使用应用程序上下文:
Instead, when you create a View programatically, you have to use the application context:
TextView label = new TextView(getApplicationContext());
二:
当您链接被拉伸到一个视图,它保持回调经由语境下的活动。如果你不去管它,它会泄漏内存,当你的活动是摧毁。
When you link a Drawable to an View, it keeps a callback on your activity via the Context. If you leave it, it will leak memory when your activity is destroy.
要做到避免的事情是设置存储可绘制'回调空当活动被破坏,因此例如蒙山一个ImageView的:
The thing to do to avoid that is to "set stored drawables' callbacks to null when the activity is destroyed" so for example whith an ImageView:
protected void onDestroy() {
imageView.getDrawable().setCallback(null);
super.onDestroy();
}
您必须为背景绘制做同样的...
You have to do the same for the background drawable...
希望它帮助。
这篇关于Android的 - 内存泄漏还是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!