使用您的答案作为提示,我再次搜索,并在互联网上找到了一些好东西,它就在这里(关于 Singleton-Activity-Service 生命周期):
http://www.2linessoftware.com/2010/08/03/singletons-and-services-and-shutdowns-oh-my/
这里有很好的相关答案:
Android中的单例与应用程序上下文?
我一直在玩 Singleton,发现答案并不完全正确。我试图在活动 A 中创建单例 S,然后转到活动 B(在离开 A 之前,我调用了 A.finish() ,并在 B.onCreate() 中调用 System.gc() ) - 但是 S.finalize( ) 不叫!
以下是代码:
public class FirstAct extends Activity implements OnClickListener {
public static final String TAG = "Test_Service";
private View btChange;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.gc();
setContentView(R.layout.first_lay);
btChange = findViewById(R.id.btChange);
btChange.setOnClickListener(this);
SomeSingleton.getInstance();
}
@Override
public void onClick(View v) {
Intent i = new Intent(this,SecAct.class);
startActivity(i);
this.finish();
}
@Override
protected void onDestroy() {
Log.i(TAG,"First activity is destroyed !");
super.onDestroy();
System.gc();
}
}
第二个活动:
public class SecAct extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.gc();
setContentView(R.layout.first_lay);
((TextView) findViewById(R.id.tvLabel)).setText("Second activity");
findViewById(R.id.btChange).setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent i = new Intent(this,FirstAct.class);
this.startActivity(i);
this.finish();
}
@Override
protected void onDestroy() {
Log.i(FirstAct.TAG,"Second activity is destroyed !");
super.onDestroy();
System.gc();
}
}
单身人士:
public class SomeSingleton {
private static volatile SomeSingleton instance = null;
private static int count = 0;
private SomeSingleton() {
count++;
Log.i(FirstAct.TAG, "Created, instance: #" + count);
}
public static SomeSingleton getInstance() {
if ( instance == null ) {
instance = new SomeSingleton();
}
return instance;
}
@Override
protected void finalize() throws Throwable {
Log.i(FirstAct.TAG, "Finalized! ");
super.finalize();
}
public void kill() {
instance = null;
}
}