![](/img/trans.png)
[英]How to manually Destroy an IntentService and Destroy it When App Close
[英]How to destroy static field when app exits?
我的應用程序中有一個singleton
類,其定義類似於:
public class SingletonTest {
private SingletonTest() {}
private static SingletonTest instance = new SingletonTest();
public static SingletonTest getInstance() {
return instance;
}
}
當我退出應用程序並再次打開時,該instance
尚未再次初始化,因為前一個instance
沒有被破壞並且仍在JVM中。 但是我想要的是每次我進入應用程序時都要初始化靜態字段。 那么,我應該在onDestroy()
方法中做什么? 非常感謝!
只要您的應用程序保留在內存中,您的靜態變量就會保留在內存中。 這意味着,靜態變量將與您的應用程序一起被自動銷毀。
如果您想要單例的新實例,則需要創建一個靜態方法來重新初始化單例,並在應用程序對象的onStart或您啟動的第一個活動中(或需要時)調用它
private Singleton() {}
private static Singleton mInstance;
//use this method when you want the reference
public static Singleton getInstance() {
//initializing your singleton if it is null
//is a good thing to do in getInstance because
//now you can see if your singleton is actually being reinitialized.
//e.g. after the application startup. Makes debugging it a bit easier.
if(mInstance == null) mInstance = new Singleton();
return mInstance;
}
//and this one if you want a new instance
public static Singleton init() {
mInstance = new Singleton();
return mInstance;
}
這樣的事情應該做。
用您的話來說,似乎Singleton不適合您想要做的事。 您應該聲明一個實例變量,該實例變量將通過onCreate()/onStart()
和onStop()/onDestroy()
方法初始化/清除。
有關活動生命周期,請參見此圖 。
來源: http : //developer.android.com/reference/android/app/Activity.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.