4

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?

3
  • @Amorogos: use refresh handler to refresh that piece of code with appropriate time dealy Commented Oct 19, 2012 at 14:10
  • But I only want to run it once when the user Launches the app. Commented Oct 19, 2012 at 14:12
  • What is it supposed to do ? is it a temporal issue ? then you could compare the time of the last execution. Commented Oct 19, 2012 at 14:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was trying to do this but was missing the static declaration.
2

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

1 Comment

Please, full code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.