前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >FLAG_ACTIVITY_NEW_TASK使用场景及原理简析

FLAG_ACTIVITY_NEW_TASK使用场景及原理简析

作者头像
全栈程序员站长
发布2022-11-08 14:46:39
8770
发布2022-11-08 14:46:39
举报
文章被收录于专栏:全栈程序员必看

在非Activity(比如Service,BroadcastReceiver)中startActivity需要添加flag Intent.FLAG_ACTIVITY_NEW_TASK。否则会报Crash:android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.

原文地址

以下Service为前提说明

简单来说:

每个Activity启动都需要依赖一个Task栈,在Service中启动Activity时一般使用ApplicationContext,它没自己的Task栈,(Activity有自己的栈,但Service中保存Activity实例容易造成内存泄漏)。

补充说明:

在MainActivity启动时,系统自动创建了App的Task栈,并且taskAffinity默认为包名:com.test.haha。 以下为三种情况:

  • 情况1:只在Activity添加FLAG_ACTIVITY_NEW_TASK 使用Task栈和MainActivity的Task栈是一样的,因为没有在AndroidMainfest添加taskAffinity,那么taskAffinity的默认值为包名即com.test.haha
  • 情况2:只在AndroidMainfest添加taskAffinity 不添加flag,无效
  • 情况3:同时在Activity添加FLAG_ACTIVITY_NEW_TASK 和 在AndroidMainfest添加taskAffinity(若指定为包名,则转到情况1) 则创建新的Task栈,行为同启动模式singleTask。

可以使用adb shell dumpsys activity activities 或者 打印getTaskId()来验证。

请参考Google文档:任务和返回栈

注意: 当调用者需要从启动的Activity获取返回结果时,不能使用此标志。即使用startActivityForResult()要注意,没有返回值的。(见官网注释最后一句)

官网注释:

FLAG_ACTIVITY_NEW_TASK

If set, this activity will become the start of a new task on this history stack. A task (from the activity that started it to the next task activity) defines an atomic group of activities that the user can move to. Tasks can be moved to the foreground and background; all of the activities inside of a particular task always remain in the same order. See Tasks and Back Stack for more information about tasks.

This flag is generally used by activities that want to present a “launcher” style behavior: they give the user a list of separate things that can be done, which otherwise run completely independently of the activity launching them.

When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in. See FLAG_ACTIVITY_MULTIPLE_TASK for a flag to disable this behavior.

This flag can not be used when the caller is requesting a result from the activity being launched.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/185379.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年10月6日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简单来说:
  • 补充说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档