Initialize application with Application class

Updated

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.

Basics

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:

package com.tanelikorri.android.initializeapplication;

import android.app.Application;
import android.util.Log;

public class ExampleApplication extends Application {

    @Override
    public void onCreate() {
        super.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:

<application
    android:name=".ExampleApplication"
    ... >
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

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

Comments

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