Correct way to get the instance of Application in android

10,669

I would recommend method 3 if you only need the instance of the Application.

I would recommend method 1 if you had additional methods in your Application class because you can more clearly do

MyApplication.getInstance().foo();

Method 2 is just a shortcut for method 3, so I wouldn't recommend it.


All in all, it's a matter of preference. There is no one "correct" way because they'll all work.

Share:
10,669
Olegvarmy
Author by

Olegvarmy

Updated on July 20, 2022

Comments

  • Olegvarmy
    Olegvarmy almost 2 years

    Which of these ways is more proper for getting the instance of Application

    1. Initialise static field in Application.onCreate() and provide static access to it

      public class MyApplication extends Application {
      
          private static MyApplication sInstance;
      
          @Override
          public void onCreate() {
              super.onCreate();
              sInstance = this;
          }
      
          public static MyApplication getInstance() {
              return MyApplication.sInstance;
          }
      }
      
      public class MyBroadcastReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
              MyApplication application = MyApplication.getInstance();
          }
      }
      
    2. Create static method which takes Context as param and cast that Context to MyApplication

      public class MyApplication extends Application {
      
          @Override
          public void onCreate() {
              super.onCreate();
          }
      
          public static MyApplication getInstance(Context context) {
              return ((MyApplication) context.getApplicationContext());
          }
      }
      
      public class MyBroadcastReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
              MyApplication application = MyApplication.getInstance(context);
          }
      } 
      
  • from56
    from56 over 3 years
    Your code returns true or false, not the application instance
  • Mohit Rajput
    Mohit Rajput about 3 years
    Making context and application instance static is not a good way. This can leak memory.
  • OneCricketeer
    OneCricketeer about 3 years
    @Mohit Feel free to write your own answer, then