Correct way to get the instance of Application in android

百般思念 提交于 2019-12-11 00:28:00

问题


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);
        }
    } 
    

回答1:


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.




回答2:


If you really want to Application instance then you're both ways are wrong. This will cause locking while access Instance at the same time. So to overcome this and improve the performance better to use synchronized

Take a look my way below

  public static MyApplication getInstance() {
    if (sInstance == null) {
        synchronized (MyApplication.class) {
            if (sInstance == null) {
                sInstance = new MyApplication();
            }
        }
    }

    return applicationInstance;
}

sInstance that you initialized in onCreate(...)



来源:https://stackoverflow.com/questions/35765077/correct-way-to-get-the-instance-of-application-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!