3

I want to run a small piece of code each time the app starts up. I have tried the following:

  • In the Activity.onCreate(). But this won't work as the activity could get re-created on rotation for example.
  • Create a subclass of Application and run in onCreate() there. This doesn't seem to work either. It gets executed when the app is installed, but not when you back-out of the application and go into it again.

Any ideas?

Eurig Jones
  • 8,226
  • 7
  • 52
  • 74

2 Answers2

4

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.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
1

This is a duplicate of How can I execute something just once per application start?

  • Create a subclass of Application and run in onCreate() there. This doesn't seem to work either. It gets executed when the app is installed, but not when you back-out of the application and go into it again

You need to put your code in the constructor and not in the onCreate() method. Check this answer: https://stackoverflow.com/a/13809300/2005891

Community
  • 1
  • 1
pepipe
  • 61
  • 8