重新创建应用程序实例时,getApplicationContext()返回null

时间:2019-11-01 11:22:29

标签: android android-context android-application-class

我正在尝试使用应用程序的上下文来启动活动,

这有效

public class MyApplication extends Application {

    public static Context mContext = null;

    public MyApplication() {
        mContext = this;
    }
    public static void launchActivity() {
        Log.i(TAG, "Going to start main activity");
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(mContext.getPackageName(), MainActivity.class.getName()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
        Log.i(TAG, "Successfully started the activity");
    }
}

这行不通

public class MyApplication extends Application {

    public MyApplication() {
        //Do nothing
    }
    public void launchActivity() {
        Log.i(TAG, "Going to start main activity");
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(getApplicationContext().getPackageName(), MainActivity.class.getName()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplicationContext().startActivity(intent);
        Log.i(TAG, "Successfully started the activity");
    }
}

我正在从广播接收器中调用此方法launchActivity,看起来与此类似,

public class MyReceiver extends BroadcastReceiver {

    public static final String TAG = "xyz";

    @Override
    public void onReceive(Context context, Intent intent) {
        MyApplication myApplication = new MyApplication();
        myApplication.upateUIModeValueViaBroadcast();
    }
}

我不理解为什么当应用程序实例是新的时,getApplicationContext()为什么返回我 null

0 个答案:

没有答案