启动Activity FLAG_ACTIVITY_NEW_TASK

版权声明:欢迎转载 有不明白的 写的不正确的地方 欢迎一起讨论 谢谢 https://blog.csdn.net/qq_27744987/article/details/80479709
  • 一般来说当我们从launcher中启动一个应用进入到ActivityA中,系统会为这个应用生成一个新任务堆栈并置于前台,ActivityA被放入栈底,之后从ActivityA启动另一个ActivityB,如果不设置什么附加属性,ActivityB默认也放到和ActivityA这个堆栈中,这样当你按返回时,B出栈,A呈现出来了,这个应该很好理解。
  • 那现在假如ActivityA启动一个Service或者发一个广播,这都是后台的话,和我们的任务栈没有关系,现在假如我们在广播中需要启动一个Activity,当然需要为这个Activity指定或分配一个任务栈 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().

  • 问题总结:
    在Activity上下文之外启动Activity需要给Intent设置FLAG_ACTIVITY_NEW_TASK标志,不然会报异常。

    android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

猜你喜欢

转载自blog.csdn.net/qq_27744987/article/details/80479709