小编Ole*_*rmy的帖子

在android中获取Application实例的正确方法

以下哪种方式更适合获取Application的实例

  1. 在 Application.onCreate() 中初始化静态字段并提供对它的静态访问

    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();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建以 Context 作为参数的静态方法并将该 Context 转换为 MyApplication

    public class MyApplication extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
        }
    
        public static MyApplication getInstance(Context context) {
            return ((MyApplication) …
    Run Code Online (Sandbox Code Playgroud)

android applicationcontext

9
推荐指数
1
解决办法
9023
查看次数

标签 统计

android ×1

applicationcontext ×1