Why extend the Android Application class?
Solution 1:
Introduction:
- If we consider an
apk
file in our mobile, it is comprised of multiple useful blocks such as,Activity
s,Service
s and others. - These components do not communicate with each other regularly and not forget they have their own life cycle. which indicate that they may be active at one time and inactive the other moment.
Requirements:
- Sometimes we may require a scenario where we need to access a
variable and its states across the entire
Application
regardless of theActivity
the user is using, - An example is that a user might need to access a variable that holds his
personnel information (e.g. name) that has to be accessed across the
Application
, - We can use SQLite but creating a
Cursor
and closing it again and again is not good on performance, - We could use
Intent
s to pass the data but it's clumsy and activity itself may not exist at a certain scenario depending on the memory-availability.
Uses of Application Class:
- Access to variables across the
Application
, - You can use the
Application
to start certain things like analytics etc. since the application class is started beforeActivity
s orServices
s are being run, - There is an overridden method called onConfigurationChanged() that is triggered when the application configuration is changed (horizontal to vertical & vice-versa),
- There is also an event called onLowMemory() that is triggered when the Android device is low on memory.
Solution 2:
Application class is the object that has the full lifecycle of your application. It is your highest layer as an application. example possible usages:
-
You can add what you need when the application is started by overriding onCreate in the Application class.
-
store global variables that jump from Activity to Activity. Like Asynctask.
etc