I want to run a small piece of code each time the app starts up. I have tried the following:
Any ideas?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With