Application class in Android

January 6, 2018 Oclemy 1 minute, 35 seconds

Android provides a base class in the android.app package which can be used to maintain the global state of an application.

Obviously activities are used extensively in almost all applications as they are a core component of android platform. However, an activity can only keep an activity state.

If the system or you destroy an activity then that state is lost. So android.app.Application provide a way for us to maintain state that is global to all activities.

To provide your own implementation of the Application class, you specify the the name in the <application> tag inside your android_manifest.xml file. Doing this ensures that during the creation of your application's process, the Application gets instantiated automatically for you.

However, when it comes to maintaining global state, it's recommended to use static singletons whenever possible since they are more modular.

Application class Methods

Here are some public methods in the android.app.Application.

Method Description
onCreate() This method gets called when tha application has been created and is starting. By this time still there is no actiity, service or receiver objects(excluding content providers) created. You have to call the onCreate() method of the super Application class: super.OnCreate().
onConfigurationChanged() This method will be called by the system when the device configuration changes are detected. Only activities get restarted when this occurs. Other components don't and have to deal with the consequences of this change such as re-fetching resources they were using.
onLowMemory() The android system will call this method when it's running low on memory. By this time the memory is low and actively running process need to trim their memory usage. This can happen at any time with no specific defined time. However by this time probably all background processes have already been killed. Typically you implement this so as to release caches and other non-critical resources you are occupying.

Comments