Search code examples
androidandroid-activityactivity-lifecycleonpause

Understanding onPause() and onSaveInstance() during configuration change and killing the application


onPause() and onSaveInstance() is always called in case of configuration changes.However in one exceptional case if programmer is handling configuration changes than in that case it will not call these methods.

What does it mean by "if programmer is handling configuration changes"?Does it mean that if programmatically we are changing orientation of device then these methods will not get called?

onPause() is the only function which will be called without fail before killing the application.So we should save all persistent data in onPause() only.

But if we are finishing our activity inside onCreate by calling finish() method then onDestroy() is directly called and onPause(),onStop() are not called.


Solution

  • What does it mean by "if programmer is handling configuration changes".Does it mean that if programmatically we are changing orientation of device then these methods will not get called?

    It means you as a programmer has to manually set what happens when configuration changes. This method will be called.

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    
        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }
    

    So, you handle what happens if orientation and other configuration changes.

    But if we are finishing our activity in onCreate by calling finish() method then onDestroy() is directly called and onPause,onStop are not called.

    If you want to explicitly destroy activity by calling finish, you should override onDestroy method and do the clean up. We're talking about what happens if your app is change on runtime, i.e phone calls happens, rotation change, etc.