启动Activity FLAG_ACTIVITY_NEW_TASK

  • 一般来说当我们从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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值