广播接收者BroadcastReceiver启动Activity需要加FLAG_ACTIVITY_NEW_TASK

BroadcastReceiver启动Activity需要加FLAG_ACTIVITY_NEW_TASK

BroadcastReceiver->onReceive的时候传进来的context是ReceiverRestrictedContext,然而ReceiverRestrictedContext的代码很简单,里面没有startActivity方法,而ReceiverRestrictedContext是继承自ContextWrapper,ContextWrapper的startActivity方法如下:

public void startActivity(Intent intent, Bundle options) {
    warnIfCallingFromSystemProcess();
    if((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
        thrownew AndroidRuntimeException(
                "Calling startActivity() from outside of an Activity "
                        +" context requires the FLAG_ACTIVITY_NEW_TASK flag."
                        +" Is this really what you want?");
    }
    mMainThread.getInstrumentation().execStartActivity(
            getOuterContext(), mMainThread.getApplicationThread(), null,
            (Activity)null, intent, -1, options);
}

FLAG_ACTIVITY_NEW_TASK的意义,官方的文档解释为:“Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().”

参考博客链接:https://blog.csdn.net/dct8888/article/details/52064160

发布了25 篇原创文章 · 获赞 0 · 访问量 590

猜你喜欢

转载自blog.csdn.net/u011609120/article/details/103871669