BLOGS

Product Engineering Outsourcing, Tech Talk

Android Application Class

A commonly used class in any application, whether it is a desktop application or a mobile application is an application level class. An application level class also called a controller is a single instance available across the application and visible to all modules within an application. This application controller can be used to maintain global state across an application, contain common methods, etc.

Android provides support in every application to create an application wide class. The base class for this is the android.app.Application class. The official documentation of the Application class is given below:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml’s <application> tag, which will cause that class to be instantiated for you when the process for your application/package is created.

Let us look at how to incorporate an Application class in our Android applications.

Step 1: Provide an implementation of the Application class

You need to extend the android.app.Application class and override the OnCreate method. This method is invoked by the Android runtime once when your application is started. So this is a good point to do application initialization and set some global settings like shared preferences, etc.

Specify your application class in the Android manifest.xml file. Each Android manifest has the <application> tag and you need to provide the application class as an attribute of this element as shown below:

The main method is getApplicationContext(). This gives an instance to the Application class if defined in the application. You need to simply type cast it to your provided Application implementation class. Once you have this instance, you can invoke any public methods that you would have defined in the class. Additionally, if you provide getter/setter methods for application wide state variables, you can invoke them too.

Having an Application wide controller in your application is a commonly used design with significant benefits. Instead of rolling out your own custom implementation, Android provides a simple mechanism to introduce it in your applications, letting you focus on your Application wide logic while it takes care of its lifecycle methods. Start using the Application class to bring in structure to your applications today.

2 comments on “Android Application Class”

Thanks — I’ve been very confused about getApplication() and getApplicationContext() — never realized I could cast the later into my application class. This is because I Activity.getApplication() exists, but in a BroadcastReceiver.onReceive(), you only get passed a Context instance and the context instance only has getApplicationContext(). This just made my eyes open!