How to use the Application object of Android

We know there is an Application class in the Android api and according to the class name it’s used for global settings or running entrance. What does it to do for an application? I will dive into it along with some examples in this blog post.

In the Android reference it describes the Application class: “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 tag, which will cause that class to be instantiated for you when the process for your application/package is created.”

So you can create your own subclass of Application like this:

And specify its name in your AndroidManifest.xml’s tag

The Application class is mainly used for some Application level callbacks and for maintaining global Application state.

Application level callbacks

  • onConfigurationChanged( ) Called by the system when the device configuration changes while your component is running.
  • onCreate( ) Called when the application is starting, before any other application objects have been created.
  • onLowMemory( ) This is called when the overall system is running low on memory, and would like actively running processes to tighten their belts.
  • onTerminate( ) 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.

Maintaining global Application state

Sometimes you want to store data, like global variables which need to be accessed from multiple Activities – sometimes everywhere within the application. In this case, the Application object will help you.

For example, if you want to get the basic authentication data for each http request, you can implement the methods for authentication data in the application object.

After this,you can get the username and password in any of the activities like this:

And finally, do remember to use the Application object as a singleton object: