Initialize application with Application class

Updated in Android

When writing Android applications there’s usually need to run some initialization code once every time the app starts.

In Android, this can be achieved with the Application class. It is guaranteed that there’s only one Application class available for each application and that the Application.onCreate method is called only once for each application instance.


In order to use the Application class, there’s two things that need to be done.

First, a new class extending the Application class needs to be created. Here I have a ExampleApplication which writes a log when the app is initialized:


import android.util.Log;

public class ExampleApplication extends Application {

    public void onCreate() {

        Log.d("ExampleApplication", "onCreate method called");

Second, this new class needs to be set as the application class in the AndroidManifest.xml file with the android:name attribute:

    ... >
    <activity android:name=".MainActivity">
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

With this setup the ExampleApplication is created and its onCreate method is called when the application starts. The onCreate method is called only once during the application lifetime so it’s the perfect place for initialization.

Source code

Source code for the whole example project is available here

Further reading


Did you find this article helpful? Or are there parts that need some improving? Write your comment below and let me know what you think!

comments powered by Disqus