Android任务栈和activity的跳转中需要特别注意的问题

本文深入探讨了Android中Activity的启动模式,特别是singleTask模式的行为,包括如何通过Intent标志和Manifest文件配置启动模式,以及这些配置如何影响Activity在任务栈中的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

google官方的文档已经对回退栈、task等机制做了详细解释
https://developer.android.com/guide/components/activities/tasks-and-back-stack
这里着重讲一些容易误解的问题。

一、我们可以通过intent.addflag和manifest两种方式设置launch mode,但是当我们同时设定时,addflag的优先级会高于manifest。

二、

However, if you start an activity that specifies the singleTask launch mode, then if an instance of that activity exists in a background task, that whole task is brought to the foreground. At this point, the back stack now includes all activities from the task brought forward, at the top of the stack. Figure 4 illustrates this type of scenario.

如果我们通过Activity A采用singleTask模式打开一个Activity B,而B在某个任务栈里已经有实例,则系统会将整个任务栈搬到前台,此时我们再按返回键,则不会回到A,而是回到这个任务栈里B底下的C。

三、

A new activity is, by default, launched into the task of the activity that called startActivity(). It’s pushed onto the same back stack as the caller. However, if the intent passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. Often, it’s a new task. However, it doesn’t have to be. If there’s already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task.
一个新的activity默认与创立他的activity在同一个任务栈里。新的activity与通过startActivity()调用他的activity在同一个任务栈中。然而,如果在startActivity()中加入FLAG_ACTIVITY_NEW_TASK flag,则系统会寻找一个不同的任务栈来放置这个activity。通常,是在一个新的任务栈里。但是,并不是必须如此。如果已经存在一个任务栈与新activity指定的affinity同名,则activity就加载到这个任务栈中。如果没有,就新建一个任务栈。

google称singleTask会为Activity新建一个task,实际上是有条件的:即必须修改相应activity的taskAffinity属性,通过taskAffinity声明这个Activity是在哪个任务栈里具有唯一性。
很多人用singleTask的时候没有添加taskAffinity,系统会默认为当前这个app的任务栈,所以实际上这个activity与该app的其他activity是在同一个栈里面,这样就没办法解决第二点的问题。所以如果想要activity跟其他activity在不同栈,记得添加taskAffinity属性。

如果没有添加taskAffinity属性,当我们通过startActivity()打开新的activity,系统会为这个activity查看是否有存在与taskAffinity名字相同的任务栈,由于我们没有定义taskAffinity,所以系统默认是该app的任务栈,查找后发现已经存在一个任务栈,于是就把我们的新activity放置在这个任务栈顶端。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值