Android:AlertDialog 导致内存泄漏
我的应用程序显示一个 AlertDialog
,其中包含一个 ListView
。一切都很好,然后我决定测试一下内存泄漏。运行应用程序一段时间后,我打开 MAT 并生成泄漏可疑报告。 MAT 发现了几个类似的漏洞:
“<系统类加载器>”加载的“com.android.internal.app.AlertController$RecycleListView”的一个实例占用...
我花了很多时间寻找这次泄漏的原因。代码审查对我没有帮助,我开始谷歌搜索。这就是我发现的:
问题 5054:AlertDialog 似乎通过 MessageQueue 中的消息导致内存泄漏< /a>
我决定检查这个错误是否会重现。为此,我创建了一个由两项活动组成的小程序。 MainActivity
是一个入口点。它仅包含一个运行 LeakedActivity
的按钮。后者仅在其 onCreate()
方法中显示一个 AlertDialog
。代码如下:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(
new Intent(MainActivity.this, LeakedActivity.class));
}
});
}
}
public class LeakedActivity extends Activity {
private static final int DIALOG_LEAK = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
showDialog(DIALOG_LEAK);
}
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_LEAK) {
return new AlertDialog.Builder(this)
.setTitle("Title")
.setItems(new CharSequence[] { "1", "2" },
new OnClickListener() {
private final byte[] junk = new byte[10*1024*1024];
@Override
public void onClick(DialogInterface dialog, int which) {
// nothing
}
})
.create();
}
return super.onCreateDialog(id);
}
}
每次 AlertDialog
被关闭且 LeakedActivity
时,MAT 都会报告此应用程序泄漏 com.android.internal.app.AlertController$RecycleListView
完成了。
我在这个小程序中找不到任何错误。它看起来像是使用 AlertDialog
的一个非常简单的案例,它必须工作得很好,但看起来却不然。所以我想知道在将 AlertDialog
与项目一起使用时如何避免内存泄漏。为什么这个问题还没有得到解决?提前致谢。
My application shows an AlertDialog
with a ListView
inside. Everything worked fine bun then I decided to test this for memory leaks. After running the app for some time I opened MAT and generated Leak Suspects report. MAT found several similar leaks:
One instance of "com.android.internal.app.AlertController$RecycleListView" loaded by "<system class loader>" occupies ...
I spent a lot of time searching for the reason of this leak. Code review didn't help me and I started googling. That's what I found:
Issue 5054: AlertDialog seems to cause a memory leak through a Message in the MessageQueue
I decided to check whether this bug reproduces or not. For this purpose I created a little program which consists of two activities. MainActivity
is an enrty point. It contains only a buttons which runs LeakedActivity
. The latter just shows an AlertDialog
in its onCreate()
method. Here's the code:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(
new Intent(MainActivity.this, LeakedActivity.class));
}
});
}
}
public class LeakedActivity extends Activity {
private static final int DIALOG_LEAK = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
showDialog(DIALOG_LEAK);
}
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_LEAK) {
return new AlertDialog.Builder(this)
.setTitle("Title")
.setItems(new CharSequence[] { "1", "2" },
new OnClickListener() {
private final byte[] junk = new byte[10*1024*1024];
@Override
public void onClick(DialogInterface dialog, int which) {
// nothing
}
})
.create();
}
return super.onCreateDialog(id);
}
}
MAT reports this application leaks com.android.internal.app.AlertController$RecycleListView
every time the AlertDialog
is dismissed and the LeakedActivity
is finished.
I can't find any error in this small program. It looks like a very simple case of using AlertDialog
and it must work well but seems it doesn't. So I'd like to know how to avoid memory leaks when using AlertDialog
s with items. And why hasn't this problem been fixed yet? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
(2/12/2012):请参阅下面的更新。
这个问题实际上并不是由
AlertDialog
引起的,而是与ListView
有关。您可以使用以下活动重现相同的问题:多次旋转设备,您将遇到 OOM。
我没有时间更多地调查真正的原因是什么(我知道发生了什么,但不清楚为什么会发生;可能是错误,也可能是设计的)。但您可以采取以下一种解决方法,至少可以避免您的情况出现 OOM。
首先,您需要保留对泄露的
AlertDialog
的引用。您可以在onCreateDialog()
中执行此操作。当您使用setItems()
时,AlertDialog
将在内部创建一个ListView
。当您在setItems()
调用中设置onClickListener()
时,它会在内部分配给ListView
onItemClickListener()
。然后,在泄漏活动的
onDestroy()
中,将AlertDialog
的ListView
的onItemClickListener()
设置为null
,这将释放对侦听器的引用,并使该侦听器中分配的任何内存都符合 GC 的条件。这样你就不会出现OOM。这只是一个解决方法,真正的解决方案实际上应该合并到ListView
中。下面是
onDestroy()
的示例代码:更新 (2/12/2012): 经过进一步调查,这个问题实际上与
ListView< 没有特别关系。 /code> 也不是
OnItemClickListener
,而是事实上 GC 不会立即发生,需要时间来决定哪些对象符合条件并准备好进行 GC。试试这个:旋转几次,你就会得到 OOM。问题是在你旋转之后,垃圾仍然被保留,因为 GC 还没有也不可能发生(如果你使用 MAT,你会看到这个垃圾仍然被 GCroot 深处的按钮监听器保留,GC 需要时间来决定这个
垃圾
是否符合条件并且可以被 GC 处理。)但同时,一个新的 <代码>垃圾需求在轮换后创建,并且由于mem分配大小(每个垃圾10M),这将导致OOM。解决方案是中断对侦听器(垃圾所有者)的任何引用,在本例中是从按钮,这实际上使侦听器作为 GCroot,只有到垃圾的短路径,并让 GC 做出决定更快地回收垃圾内存。这可以在
onDestroy()
中完成:(2/12/2012): see UPDATE below.
This problem is not actually caused by the
AlertDialog
but more related to theListView
. You can reproduce the same problem by using the following activity:Rotate the device several times, and you'll get OOM.
I haven't got the time to investigate more on what is the real cause (I know what's happening but not clear why it's happening; can be bug, or designed). But here's one workaround that you can do, at least to avoid the OOM in your case.
First, you'll need to keep a reference to your leaked
AlertDialog
. You can do this in theonCreateDialog()
. When you're usingsetItems()
, theAlertDialog
will internally create aListView
. And when you set theonClickListener()
in yoursetItems()
call, internally it will be assigned to theListView
onItemClickListener()
.Then, in the leaked activity's
onDestroy()
, set theAlertDialog
'sListView
'sonItemClickListener()
tonull
, which will release the reference to the listener an make whatever memory allocated within that listener to be eligible for GC. This way you won't get OOM. It's just a workaround and the real solution should actually be incorporated in theListView
.Here's a sample code for your
onDestroy()
:UPDATE (2/12/2012): After further investigation, this problem is actually not particularly related to
ListView
nor toOnItemClickListener
, but to the fact that GC doesn't happen immediately and need time to decide which objects are eligible and ready for GC. Try this:Rotate a couple of times, and you'll get the OOM. The problem is after you rotate, the
junk
is still retained because GC hasn't and can't happen yet (if you use MAT, you'll see that thisjunk
is still retained by the button's listener deep down from the GCroot, and it will take time for the GC to decide whether thisjunk
is eligible and can be GCed.) But at the same time, a newjunk
needs to be created after the rotation, and because of the mem alloc size (10M per junk), this will cause OOM.The solution is to break any references to the listener (the
junk
owner), in this case from the button, which practically makes the listener as a GCroot with only short path to the junk and make the GC decide faster to reclaim the junk memory. This can be done in theonDestroy()
:无法重现 Android
2.3.42.3.3。我在实际设备上测试了您的确切代码,从我在 LogCat 中看到的情况来看,堆大小随着时间的推移保持不变。遗憾的是我无法 hprof-conf 我的转储(错误:期待 1.0.3)Cannot reproduce for Android
2.3.42.3.3. I Tested your exact code on a actual device and from what I see in LogCat, the heap size stays constant over time. Sadly I was not able to hprof-conf my dumps (ERROR: expecting 1.0.3)我已经运行了您的代码,当我第一次按下按钮时,它显示带有对话框的 LeakedActivity ,并且 onClick 正在删除对话框,但活动仍处于黑屏的前台。按返回键然后再次启动活动时,它显示内存超出错误异常:
然后我删除了行
private Final byte[] junk = new byte[10*1024*1024];
之后的对话框代码不存在这样的问题....不知道为什么如果有人可以用文字表达这个东西,谢谢他/她..I had run your code and when I first press the button it is showing the LeakedActivity with dialog and onClick it is removing dialog but the activity remains in foreground with black screen. On pressing back key and then again starting the activity it is showing the memory out of error exception:
Then I removed the line
private final byte[] junk = new byte[10*1024*1024];
from the dialog code after that no such problem exists....don't know why if anyone can put this thing in words, thanks to him/her..您需要从 onClick 方法中关闭/取消对话框,如示例所示: Android 中的警报对话框
You need to dismiss/cancel the dialog from the onClick method as shown in the example here : Alert Dialogs in Android