Why to extend an Application
class?
What is in it for me?
Why would you do that?
I read that it can be used to declare global variables, is that all or are there any other applications?
Why to extend an Application
class?
What is in it for me?
Why would you do that?
I read that it can be used to declare global variables, is that all or are there any other applications?
The Application class is a singleton that you can access from any activity or anywhere else you have a Context object.
You also get a little bit of lifecycle.
You could use the Application's onCreate method to instantiate expensive, but frequently used objects like an analytics helper. Then you can access and use those objects everywhere.
Not an answer but an observation: keep in mind that the data in the extended application object should not be tied to an instance of an activity, as it is possible that you have two instances of the same activity running at the same time (one in the foreground and one not being visible).
For example, you start your activity normally through the launcher, then "minimize" it. You then start another app (ie Tasker) which starts another instance of your activitiy, for example in order to create a shortcut, because your app supports android.intent.action.CREATE_SHORTCUT. If the shortcut is then created and this shortcut-creating invocation of the activity modified the data the application object, then the activity running in the background will start to use this modified application object once it is brought back to the foreground.
Introduction:
apk
file in our mobile, it is comprised of multiple useful blocks such as,Activity
s,Service
s and others.Requirements:
Application
regardless of theActivity
the user is using,Application
,Cursor
and closing it again and again is not good on performance,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:
Application
,Application
to start certain things like analytics etc. since the application class is started beforeActivity
s orServices
s are being run,Offhand, I can't think of a real scenario in which extending Application is either preferable to another approach or necessary to accomplish something. If you have an expensive, frequently used object you can initialize it in an IntentService when you detect that the object isn't currently present. Application itself runs on the UI thread, while IntentService runs on its own thread.
I prefer to pass data from Activity to Activity with explicit Intents, or use SharedPreferences. There are also ways to pass data from a Fragment to its parent Activity using interfaces.
Best use of application class. Example: Suppose you need to restart your alarm manager on boot completed.
Source: https://github.com/codepath/android_guides/wiki/Understanding-the-Android-Application-Class