Search code examples
androidlaunch

Execute code every time the application begins


I would like to execute code every time the application begins (not only the very first time the application begins so getSharedPreferences doesn't help).

I've tried to write the code in onStart() of the main Activity, but that code was executed everytime I entered the activity including times I back to this activity from other activities (so onStart() doesn't help).

If someone can direct me with this, I'll appreciate that. Thanks.


Solution

  • Create an Application class - everytime an application opens it will execute the onCreate Method.

    //Note extends Application and not Activity.
    public class MyApplication extends Application {
    
    
    @Override
    public void onCreate() {
        super.onCreate();
       //Put your code here.
    }
    

    Make sure you register this in your manifest -

       <application
        android:name=".MyApplication"
    

    Any code you put in onCreate will execute when the app is opened.