0

我正在尝试使用类似这样的应用程序上下文启动一个活动,

这有效

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 。

4

0 回答 0