我一直被这个"特性"所困扰:当我使用Back按钮离开我的应用程序时,我可以告诉onDestroy()被调用,但是下次我运行我的应用程序时,Activity类的所有静态成员仍然保留它们的值.请参阅以下代码:
public class HelloAndroid extends Activity {
private static int mValue; // a static member here
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText((mValue != 0) ?
("Left-over value = " + mValue) : "This is a new instance");
setContentView(tv);
}
public void onDestroy() {
super.onDestroy();
mValue++;
}
Run Code Online (Sandbox Code Playgroud)
}
上面的代码在mValue中显示剩余值,并在会话结束时递增,这样我就可以确定调用了onDestroy().
我在这个论坛上找到了一个有用的答案,我在上面的代码中理解mValue是一个类成员,而不是实例成员.但是,在这个特殊情况下,我只有一个HelloAndroid活动,所以当他去世时,一切都被清理干净,下次我回来时,一切都重新开始了,这不是真的吗?(或者,在onDestroy()之后,系统中还有其他一些神秘的东西仍然坚持它,这样它就不会死了吗?)
(上面只是一个变量,如果它是一堆对象引用怎么办?每个部分都是一个单独的可重新收集的内存.GC是否有机会收集其中一些而不是全部或者没有?这真的让我烦恼. )
我在ListActivity中使用以下代码
// a separate class in project
public class MyActivity extends ListActivity {
// some common functions here..
}
public class SelectLocation extends MyListActivity {
public void onCreate(Bundle savedInstance) {
// here.....
}
@Override
protected void onDestroy() {
super.onDestroy();
if (adap != null) adap = null;
if (list != null) list = null;
System.gc();
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都指导我为什么onDestroy
在我的代码中没有调用方法?