I'm confused while learning savedInstanceState Bundle. I found that the Activity instance is not destroyed after onDestroy() method is called, or it can save the data without the help of savedInstanceState Bundle.
This is my test code:
package com.example.hellotest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static int testNum = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_main);
testNum++;
Log.d(TAG, "testNum: " + testNum);
if(savedInstanceState == null)
Log.d(TAG, "savedInstanceState is null");
else
Log.d(TAG, "savedInstanceState is NOT null");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
}
And here is the log info:
11-17 22:10:14.433: D/MainActivity(23303): onCreate
11-17 22:10:14.463: D/MainActivity(23303): testNum: 1
11-17 22:10:14.463: D/MainActivity(23303): savedInstanceState is null
11-17 22:10:17.527: D/MainActivity(23303): onDestroy
11-17 22:10:18.278: D/MainActivity(23303): onCreate
11-17 22:10:18.298: D/MainActivity(23303): testNum: 2
11-17 22:10:18.298: D/MainActivity(23303): savedInstanceState is null
11-17 22:10:19.569: D/MainActivity(23303): onDestroy
11-17 22:10:20.200: D/MainActivity(23303): onCreate
11-17 22:10:20.220: D/MainActivity(23303): testNum: 3
11-17 22:10:20.220: D/MainActivity(23303): savedInstanceState is null
The testNum never returns to 1 unless I totally kill the process on the phone, which seems to me that the Activity instance is not destroyed really, so we don't need to override the onSaveInstanceState(Bundle outState) method to save the data.
Is there somewhere I'm misunderstanding?
testNumis declared asstatic, and is therefore associated with the classMainActivity, not any particular instance of it. Unless you need to accesstestNumstatically, you should remove thestaticidentifier:Doing this will result in
testNumbeing associated with an instance of theMainActivityclass, and will indeed be destroyed.You can, if you choose, override
onSaveInstanceStateto maintain instance variables across rotations or ifMainActivityis destroyed and recreated for any other configuration changes: