Saving and Restoring State in an Android App

A great user experience gives a user the ability to transition seamlessly between many apps on their device and then be able to pick up right where they left off when the app is launched again.  If an Android app is stopped on a device, the app can save the app state and then restore the state when the app is launched again by the user.  This blog shows a simple method to save and restore state in an Android app.


When an app is launched for the first time, the default values determined by the developer are used for initializing the app variables.  When the app is stopped and launched again, the values saved will be used for initializing the app variables.  The example below shows an integer called gameState that gets saved when onStop() is called and then restored when onStart() is called.  

@Override
protected void onStart()
{
        super.onStart();
     
        SharedPreferences settings = getSharedPreferences(getString(R.string.appSettings), MODE_PRIVATE);
        
        //Initialize to the default value if first run or restore the saved value
        gameState = settings.getInt(getString(R.string.gameState), GAMESTATE_DEFAULT_VAL);
}


@Override
protected void onStop()
{
    super.onStop();

    SharedPreferences settings = getSharedPreferences(getString(R.string.appSettings), MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();

        //Save Value
        editor.putInt(getString(R.string.gameState), gameState);
        editor.commit();
}

 

To learn more about the lifecycle of an Android activity, please see the link below:
http://developer.android.com/training/basics/activity-lifecycle/starting.html


To learn more about Saving Data, please see the link below:
http://developer.android.com/training/basics/data-storage/index.html

 

++This sample source code is released under the Open Source Initiative OSI - The BSD License.

For more complete information about compiler optimizations, see our Optimization Notice.