Tenho um vazamento de memória usando o ListActivity no Android
Eu tenho um aplicativo que usa um serviço e algumas atividades da lista. Quando as atividades são abertas, vejo o uso do heap aumentar no DDMS; quando as atividades são fechadas, o uso do heap diminui um pouco. O serviço ainda está sendo executado em segundo plano neste momento. Se a atividade for iniciada novamente reexecutando o aplicativo e fechada, o uso do heap aumentará novamente e depois diminuirá, mas nunca retornará ao nível original antes que a atividade fosse aberta pela primeira vez. Se ele repetidamente (10 a 15 vezes) abrir a atividade, feche a atividade, o tamanho da pilha (MB e # Objetos) aumentará!
Eu esperava que o onDestroy da ListActivity se cuidasse quando fosse destruído. O que estou perdendo com isso? Estou usando o ListActivity incorretamente?
Um aplicativo de teste semelhante ao meu código real está abaixo. Crie um novo aplicativo para Android, adicione-o ao manifesto:
<service android:name="LeakTestService"/>
e esses arquivos 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; } }