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 is an android component. However there are 4 other components. But first what is an android component?
Android Components are the building blocks of an Android app.
Android has around 5 types of components:
Each of these components plays a specific role in an Android app which serves a distinct purpose and has distinct life-cycles(the flow of how and when the component is created and destroyed).
Activities are responsible for user interface. Normally you start by creating and activity, or the IDE generating for you a MainActivity.
Services implement long running operations in the background.
BroadcastReceivers listen for System events.
ContentProviders on the other hand are used to store the application data.
All the above have to be registered in the AndroidManifest.xml file.
The above components get tied up together by use of Intents.
To learn more android components, check here.
Here are some public methods in the
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
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.