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?
In your main activity, declare a static boolean flag that you set to
truewhen you run the start-up code. InonCreate, run the start-up code only if the flag isfalse. InonDestroy(or in any of the shut-down lifecycle methods, for that matter), clear the flag if the activity is finishing: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
falsewhen 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.