15

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);
        }
    } 
    
hichris123
  • 10,145
  • 15
  • 56
  • 70
Olegvarmy
  • 199
  • 1
  • 1
  • 8
  • I do not understand one thing here. If you really want a `Context` in `BroadcastReceiver` then `onReceive(Context context,...)` already provide as a First Parameter. Use that one. – M D Mar 03 '16 at 06:54
  • 1
    I've never seen way 2, but it doesn't make sense to me because if you have a Context, you can do getApplicationContext – OneCricketeer Mar 03 '16 at 06:55

3 Answers3

6

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
2
(getActivity().getApplication() as MyApplication)

This will return the instance of MyApplication

-3

(getActivity().getApplication() instanceOf MyApplication) should be the correct way