Home » Intel » Saving and Restoring State in an Android App

Saving and Restoring State in an Android App


A perfect consumer expertise provides a person the flexibility to transition seamlessly between many apps on their device after which have the ability to choose up proper the place they left off when the app is launched once more.  If an Android app is stopped on a device, the app can store the app state after which fix the state when the app is launched once more by way of the person.  This weblog displays a easy technique to store and restoration state in an Android app.

When an app is launched for the primary time, the default values decided via the developer are used for initializing the app variables.  When the app is stopped and launched once more, the values saved can be used for initializing the app variables.  The instance under presentations an integer referred to as gameState that will get saved when onStop() is known as after which restored when onStart() is known as.  

secure void onStart()

        SharedPreferences settings = getSharedPreferences(getString(R.string.appSettings), MODE_PRIVATE);
        //Initialize to the default price if first run or repair the saved worth
        gameState = settings.getInt(getString(R.string.gameState), GAMESTATE_DEFAULT_VAL);

safe void onStop()


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

        //Store Worth
        editor.putInt(getString(R.string.gameState), gameState);

To study extra concerning the lifecycle of an Android process, please see the hyperlink under:

To analyze extra about Saving Information, please see the hyperlink beneath:

++This pattern supply code is launched underneath the Open Source Initiative OSI – The BSD License.