0

Cant figure out why onSaveInstanceState and onRestoreInstanceState isnt outputting my Logcat messages when I click the home button and when I restore the app respectively.

public class MainActivity extends ActionBarActivity {

    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        count++;
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        Log.d("TAG", count + " was restored");

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        count = savedInstanceState.getInt("count");
        Log.d("TAG", count + " was restored");
    }
}
11m0
  • 216
  • 7
  • 16

2 Answers2

2

onSaveInstanceState() and onRestoreInstanceState() are called at specific times in the activity's lifecycle.

Activity lifecycle

As you can see, for onSaveInstanceState() to be called, the activity needs to be destroyed by the operating system. Pressing the Home button will only call the onPause() method.

To debug the onSaveInstanceState() method, go into Settings -> Developer options on the Android device, and in the Apps section, check the box beside Kill app back button. Now, a long press on the back button should kill the visible app and notify you with a toast. Opening the app again will call onRestoreInstanceState().

If this option is not present on your device, or if you're using an emulator, follow the instructions here on how to immediately destroy activities to test onSaveInstanceState() and onRestoreInstanceState(): http://developer.android.com/tools/debugging/debugging-devtools.html

Community
  • 1
  • 1
Eoin
  • 833
  • 2
  • 13
  • 24
1

Clicking the home button isn't enough to kill the app. That just pauses it. onSave/onRestore are only called when the framework is going to kill the activity and restore it later on. Just minimizing it doesn't do that.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127