Android - Identify source of activity creation

     Few applications might want to know the use case in response to which its activity is created to handle internal state etc. Generally, activity is created when it is launched for the first time or in response to a configuration change ( screen orientation, keyboard, language change etc) or when the user resumes the activity from background after a low memory kill. In case of a low memory kill, when the user resumes the activity from the recent apps list, Android creates a new process and starts a new instance of the activity with the previously saved instance state. So how do we identify these three different scenarios? Thanks to an activity API isChangingConfigurations, the logic is quite simple.

    private final static String CONFIG_CHANGED = "ConfigurationChanged";

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(CONFIG_CHANGED, isChangingConfigurations());
    }

    private void detectActivityCreationSource(Bundle savedInstanceState) {
        String toastMsg;
        if ( savedInstanceState == null ) {
            toastMsg = "Activity created for first time";
        } else {
            if ( savedInstanceState.getBoolean(CONFIG_CHANGED) ) {
                toastMsg = "Activity created in response to configuration change";
            } else {
                toastMsg = "Activity created after low memory kill";
            }
        }
        Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show();
    }

    isChangingConfigurations() would return true ONLY in old activity instance. Hence, its safe to assume that it would always return false once the activity is resumed (before onSaveInstanceState is called once again after a configuration change).

No comments: