我有一个使用服务和一些列表 Activity 的应用程序。当 Activity 打开时,我可以看到 DDMS 中的堆使用量增加,当 Activity 关闭时,堆使用量略有下降。此时该服务仍在后台运行。如果通过重新运行应用程序并关闭 Activity 而再次启动该 Activity ,则堆使用会再次增加然后减少,但永远不会回到 Activity 首次打开之前的原始水平。如果它重复(10-15 次)打开 Activity 然后关闭 Activity ,堆大小(MB 和# Objects)会膨胀!
我希望 ListActivity 的 onDestroy 在它被销毁时自行处理。我错过了什么?我是否错误地使用了 ListActivity?
下面是一个类似于我的真实代码的测试应用程序。创建一个新的 android 应用程序,将其添加到 list 中:
<service android:name="LeakTestService"/>
和这些 java 文件:
LeakTestActivity.java ------------- package LeakTest.Test; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.SimpleAdapter; public class LeakActivity extends ListActivity { ArrayList> _Data=new ArrayList>(); ArrayAdapter _Adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent svc = new Intent(this.getApplicationContext(), LeakTestService.class); startService(svc); // the problem happens with both SimpleAdapter and ArrayAdapter //_Adapter = new SimpleAdapter(this.getApplicationContext(), _Data, android.R.layout.two_line_list_item, new String[] { "line1","line2" }, new int[] { android.R.id.text1, android.R.id.text2 }); _Adapter = new ArrayAdapter(this.getApplicationContext(), android.R.layout.simple_list_item_1, new String[] {"data1","data2"} ); // if this line is removed, the heap usage never balloons if you repeatedly open+close it getListView().setAdapter(_Adapter); } @Override public void onDestroy() { _Adapter=null; // this line doesn't help getListView().setAdapter(null); // neither does this line super.onDestroy(); } } LeakTestService.java -------- package LeakTest.Test; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.widget.Toast; public class LeakTestService extends Service { @Override public void onStart(Intent intent, int startId) { Toast.makeText(getBaseContext(), "Service onStart", Toast.LENGTH_SHORT).show(); } @Override public void onDestroy() { Toast.makeText(getBaseContext(), "Service onDestroy", Toast.LENGTH_SHORT).show(); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } }
最佳答案
我遇到了同样的问题,但是我发现这个问题只是在调试时出现的。在“正常”运行中,所有 Activity 都消失了。
关于android - 我在 Android 中使用 ListActivity 时发生内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3910473/