Reputation: 2075
In my Android application how do I run a specific function when the application is started? If possible, I don't want to tie it to a specific activity. Tying it to the onCreate method of a specific activity wouldn't work, because onCreate gets called even if the screen orientation changes.
Upvotes: 1
Views: 273
Reputation: 22371
For having a function that only runs once each time the application is started, you have a couple of options.
-You can create a Singleton with the function you want to run, and make the function call conditional on a static boolean flag within the singleton. Since the static singleton is external from any given Activity, the flag won't revert when you rotate your screen and create/destroy individual activities. While this solution is preferred over Application subclassing, you do need to make sure that the function call "mySingleton.runOnce(params...)" is in each Activity that constitutes an entry point for your Activity (so anywhere you can Intent into from an external app)
-You can subclass the Application class and override its onCreate method. This isn't the preferred solution: From the documentation,
There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
Hope this helps!
Upvotes: 3