In your main activity, declare a static boolean flag that you set to true
when you run the start-up code. In onCreate
, run the start-up code only if the flag is false
. In onDestroy
(or in any of the shut-down lifecycle methods, for that matter), clear the flag if the activity is finishing:
protected void onDestroy() {
super.onDestroy();
if (isFinishing()) {
startedFlag = false;
}
}
This will clear the flag when the activity is finishing but leave it untouched if the activity is being destroyed because of a configuration change.
There's still a catch: the activity's process might be killed off while paused and the app is in the background. In that case, the flag will be false
when the activity is recreated by the system when the user tries to bring the app back to the foreground. If this is a problem, then you are going to have to make the flag persistent. I'd recommend using shared preferences for that.