Why extend the Android Application class?
Asked Answered
A

13

189

An extended Application class can declare global variables. Are there other reasons?

Algebra answered 1/8, 2013 at 18:53 Comment(1)
This is just an idea off the top of my head, but you should be able to override the onCreate and show a one time start up screen rather than the MainActivity, i.e. an intro screen the first time the user opens the app.Quentinquercetin
C
33

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.

Contradictory answered 1/8, 2013 at 20:1 Comment(3)
There are many uses of extending application class. One very useful is to catch all uncaught exceptions in you application. SO this is something which can be very handyPierian
+1 for "prefer to pass data from Activity to Activity with explicit Intents, or use SharedPreferences". We should always eliminate global state as much as we can and use standard Android tools for global state management instead of static vars/singletons and etc.Dagnah
why? to prepare for android at some point running them in different processes or whatever and every component being reusable by any app, while that is intentionally limited? just passing the data objects instead of serializing them saves cpu and memory. parceling stuff for inside-process-on-same-device handovers is not ideal in any way. I really don't see the point of intentservice use like that(just do the other thread with new). really a lot of the stuff that confuses coders comes from that pretty much all the google added "helpers" are made as if the activities ran on separate computers.Eustache
R
146

Introduction:

enter image description here

  1. If we consider an apk file in our mobile, it is comprised of multiple useful blocks such as, Activitys, Services and others.
  2. 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:

  1. Sometimes we may require a scenario where we need to access a variable and its states across the entire Application regardless of the Activity the user is using,
  2. 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,
  3. We can use SQLite but creating a Cursor and closing it again and again is not good on performance,
  4. We could use Intents 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:

  1. Access to variables across the Application,
  2. You can use the Application to start certain things like analytics etc. since the application class is started before Activitys or Servicess are being run,
  3. There is an overridden method called onConfigurationChanged() that is triggered when the application configuration is changed (horizontal to vertical & vice-versa),
  4. There is also an event called onLowMemory() that is triggered when the Android device is low on memory.
Remount answered 24/10, 2015 at 7:34 Comment(2)
In your Requirement portion, why not use SharedPreferences?Kilmarnock
In the 1st example like for saving personal infos, SharedPreferences can be used. But the examples you gave in the last portion cleared my doubts. Thanks!Fidgety
B
68

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

Bassoon answered 1/8, 2013 at 18:56 Comment(3)
Using Application as a dumping ground for application-global variables is a big code smell. You should use your own custom, more specific classes as singletons or with static variables to do accomplish this.Villarreal
@Villarreal why is it a smell?Alsacelorraine
Yeah, why smell? As stated before, Application class is at the top of the hierarchy, and I can bet my lunch money, that a custom singleton class is below it. So, if push comes to shove, and your phone is low on memory, I'd say that the custom singleton is the first one to get killed, rather than the Application class (which essentially is your whole app).Bonhomie
A
37

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:

MyApplication mApplication = (MyApplication)getApplicationContext();
String username = mApplication.getUsername();
String password = mApplication.getPassword();

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

public class MyApplication extends Application {
    private static MyApplication singleton;

    public MyApplication getInstance(){
        return singleton;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        singleton = this;
    }
}

For more information, please Click Application Class

Autolycus answered 11/12, 2014 at 6:53 Comment(5)
kindly explain me this, why we need to explicitly make singleton object of an Application class, as far as I know it is itself a singleton. Can we make multiple application objects, if we can, then how? and what is the consequences? Kindly explain.Dugaid
No, Probably only one application class . developer.android.com/guide/topics/manifest/…Autolycus
then why we need to explicitly maintain singleton object of it? Is not OS maintaining it for us? Actually I encountered a code in which there is an application object made in activity class and it is not being mentioned in manifest. I think this is wrong, also I am curious why we are making static singleton object. What you think is the best approach. Thanks for replying.Dugaid
thanks I found my answer here on this link developer.android.com/reference/android/app/Application.htmlDugaid
Where is * singleton* object in thatAitken
C
33

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.

Contradictory answered 1/8, 2013 at 20:1 Comment(3)
There are many uses of extending application class. One very useful is to catch all uncaught exceptions in you application. SO this is something which can be very handyPierian
+1 for "prefer to pass data from Activity to Activity with explicit Intents, or use SharedPreferences". We should always eliminate global state as much as we can and use standard Android tools for global state management instead of static vars/singletons and etc.Dagnah
why? to prepare for android at some point running them in different processes or whatever and every component being reusable by any app, while that is intentionally limited? just passing the data objects instead of serializing them saves cpu and memory. parceling stuff for inside-process-on-same-device handovers is not ideal in any way. I really don't see the point of intentservice use like that(just do the other thread with new). really a lot of the stuff that confuses coders comes from that pretty much all the google added "helpers" are made as if the activities ran on separate computers.Eustache
V
10

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.

Victorvictoria answered 1/8, 2013 at 18:56 Comment(5)
"You also get a little bit of lifecycle." you might want to reword that.Bassoon
I mean you get some lifecycle calls, but not as many as with an activity or fragment. For example, there is no onDestroy() for the Application class.Victorvictoria
Is this class automaticaly created?Periodontics
Yes. As long as you specify it correctly in you AndroidManifest.xml.Victorvictoria
No, it is not automatically created.You have to create it and then declare it in your manifest fileRed
E
8

Best use of application class. Example: Suppose you need to restart your alarm manager on boot completed.

public class BaseJuiceApplication extends Application implements BootListener {

    public static BaseJuiceApplication instance = null;

    public static Context getInstance() {
        if (null == instance) {
            instance = new BaseJuiceApplication();
        }
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();


    }

    @Override
    public void onBootCompleted(Context context, Intent intent) {
        new PushService().scheduleService(getInstance());
        //startToNotify(context);
    }
Ephemera answered 24/11, 2015 at 13:23 Comment(2)
I am wondering why we need to make a static reference of application object, where as we can get it using getApplication() and typecast it to the application class. As far as I understood this concept that application class is made by the OS itself and it should have only one instance which is maintained by OS. Kindly explain, thanks.Dugaid
You're correct. Calling getApplication from any application component in your app returns the single Application-derived instance that is your app. This is handled internally by the Android framework. All you need to do is cast that returned instance to your custom class that extends Application. You also need to set your manifest accordingly so that the proper class is used by the Android framework to instantiate the instance.Galaxy
R
5

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.

Rossetti answered 1/5, 2015 at 18:22 Comment(0)
M
5

I see that this question is missing an answer. I extend Application because I use Bill Pugh Singleton implementation (see reference) and some of my singletons need context. The Application class looks like this:

public class MyApplication extends Application {

    private static final String TAG = MyApplication.class.getSimpleName();

    private static MyApplication sInstance;

    @Contract(pure = true)
    @Nullable
    public static Context getAppContext() {
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate() called");
        sInstance = this;
    }
}

And the singletons look like this:

public class DataManager {

    private static final String TAG = DataManager.class.getSimpleName();

    @Contract(pure = true)
    public static DataManager getInstance() {
        return InstanceHolder.INSTANCE;
    }

    private DataManager() {
        doStuffRequiringContext(MyApplication.getAppContext());
    }

    private static final class InstanceHolder {
        @SuppressLint("StaticFieldLeak")
        private static final DataManager INSTANCE = new DataManager();
    }
}

This way I don't need to have a context every time I'm using a singleton and get lazy synchronized initialization with minimal amount of code.

Tip: updating Android Studio singleton template saves a lot of time.

Megalopolis answered 30/4, 2017 at 6:52 Comment(0)
S
5

Source: https://github.com/codepath/android_guides/wiki/Understanding-the-Android-Application-Class

In many apps, there's no need to work with an application class directly. However, there are a few acceptable uses of a custom application class:

  • Specialized tasks that need to run before the creation of your first activity
  • Global initialization that needs to be shared across all components (crash reporting, persistence)
  • Static methods for easy access to static immutable data such as a shared network client object

You should never store mutable instance data inside the Application object because if you assume that your data will stay there, your application will inevitably crash at some point with a NullPointerException. The application object is not guaranteed to stay in memory forever, it will get killed. Contrary to popular belief, the app won’t be restarted from scratch. Android will create a new Application object and start the activity where the user was before to give the illusion that the application was never killed in the first place.

Solidary answered 10/2, 2018 at 21:28 Comment(0)
R
4

I think you can use the Application class for many things, but they are all tied to your need to do some stuff BEFORE any of your Activities or Services are started. For instance, in my application I use custom fonts. Instead of calling

Typeface.createFromAsset()

from every Activity to get references for my fonts from the Assets folder (this is bad because it will result in memory leak as you are keeping a reference to assets every time you call that method), I do this from the onCreate() method in my Application class:

private App appInstance;
Typeface quickSandRegular;
...
public void onCreate() {
    super.onCreate();

    appInstance = this;
    quicksandRegular = Typeface.createFromAsset(getApplicationContext().getAssets(),
                       "fonts/Quicksand-Regular.otf");
   ...
   }

Now, I also have a method defined like this:

public static App getAppInstance() {
    return appInstance;
}

and this:

public Typeface getQuickSandRegular() {
    return quicksandRegular;
}

So, from anywhere in my application, all I have to do is:

App.getAppInstance().getQuickSandRegular()

Another use for the Application class for me is to check if the device is connected to the Internet BEFORE activities and services that require a connection actually start and take necessary action.

Red answered 8/12, 2016 at 16:55 Comment(1)
Well said. Very Nice break down.Bedspring
L
2

To add onto the other answers that state that you might wish store variables in the application scope, for any long-running threads or other objects that need binding to your application where you are NOT using an activity (application is not an activity).. such as not being able to request a binded service.. then binding to the application instance is preferred. The only obvious warning with this approach is that the objects live for as long as the application is alive, so more implicit control over memory is required else you'll encounter memory-related problems like leaks.

Something else you may find useful is that in the order of operations, the application starts first before any activities. In this timeframe, you can prepare any necessary housekeeping that would occur before your first activity if you so desired.

2018-10-19 11:31:55.246 8643-8643/: application created
2018-10-19 11:31:55.630 8643-8643/: activity created
Lob answered 19/10, 2018 at 15:34 Comment(0)
A
1

You can access variables to any class without creating objects, if its extended by Application. They can be called globally and their state is maintained till application is not killed.

Adaline answered 23/9, 2014 at 14:22 Comment(0)
P
1

The use of extending application just make your application sure for any kind of operation that you want throughout your application running period. Now it may be any kind of variables and suppose if you want to fetch some data from server then you can put your asynctask in application so it will fetch each time and continuously, so that you will get a updated data automatically.. Use this link for more knowledge....

http://www.intridea.com/blog/2011/5/24/how-to-use-application-object-of-android

Persistent answered 17/7, 2015 at 9:13 Comment(1)
it is not a thread, so "for any kind of operation that you want throughout your application running period." is not true.Eustache

© 2022 - 2024 — McMap. All rights reserved.