Search code examples
androidandroid-application-class

Is extending Application how you run code before the launching Activity?


If I do something like this:

public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //init something else here if you want
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        //terminate something else here if you want
    }

}

And include the name of this class in the Manifest file like this:

<application
        android:name="com.packagename.MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

Is this effectively giving us a way to run whatever code we want before and after the app runs?

Edit: If I step into the onCreate() statement I see this in the code:

/**
     * Called when the application is starting, before any activity, service,
     * or receiver objects (excluding content providers) have been created.
     * Implementations should be as quick as possible (for example using 
     * lazy initialization of state) since the time spent in this function
     * directly impacts the performance of starting the first activity,
     * service, or receiver in a process.
     * If you override this method, be sure to call super.onCreate().
     */
    @CallSuper
    public void onCreate() {
    }

    /**
     * This method is for use in emulated process environments.  It will
     * never be called on a production Android device, where processes are
     * removed by simply killing them; no user code (including this callback)
     * is executed when doing so.
     */
    @CallSuper
    public void onTerminate() {
    }

Edit 2: I could also save the application context as a global static variable:

public class MyApp extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        MyApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApp.context;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}

Solution

  • Yes. The main reason of having it extend Application class

    • Is to have all initialization that you want to be singletons throughout the app and used in components.
    • Have some static variables to be used across components

    Ref: Logic why we should use