Hamid
Hamid

Reputation: 4430

Android, get previous state of activity?

I need to get the state the activity just came out of, for example, I need to run some code in my onResume(), but only after it is called following onPause() and not on following on Start().

If onResume() is called after onStop() then I need to run some different code.

How should I properly check this?

Upvotes: 1

Views: 2219

Answers (1)

dave.c
dave.c

Reputation: 10908

Here is the lifecycle. I think you can save a flag into your preferences and check it during onResume. Here's some pseudo-code:

onStart() {
    saveFlagToPreferences(false);
}

onResume() {
    boolean doStuff = getFlagFromPrefs();
    if (doStuff) {
        //do some stuff following onPause
    } else {
        //do some stuff following onStop
    }
}

onPause() {
    saveFlagToPreferences(true);
}

onStop() {
    saveFlagToPreferences(false);
}

To load the preferences you can use something like:

SharedPreferences settings = getSharedPreferences("MyAppName",0);
settings.getBoolean("flag", true);  

And to save them:

SharedPreferences settings = getSharedPreferences("MyAppName",0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag",true);
editor.commit();

Upvotes: 1

Related Questions