Intent-- FLAG_ACTIVITY_CLEAR_TOP

本文介绍了Android中FLAG_ACTIVITY_CLEAR_TOP标志的作用。当设置此标志启动Activity B时,如果任务栈中已存在B,栈中B以上的Activity(如C和D)会被结束,栈顶变为接收intent的B。启动模式不同,B接收intent的方式也不同:标准模式下B会销毁并重建,其他模式则通过onNewIntent()接收。

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

今天在项目中接触到了这么一个关键字,记录下来以备以后查看。

首先来看代码:

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

intent的源码,官方的解释如下:

/**
     * If set, and the activity being launched is already running in the
     * current task, then instead of launching a new instance of that activity,
     * all of the other activities on top of it will be closed and this Intent
     * will be delivered to the (now on top) old activity as a new Intent.
     *
     * <p>For example, consider a task consisting of the activities: A, B, C, D.
     * If D calls startActivity() with an Intent that resolves to the component
     * of activity B, then C and D will be finished and B receive the given
     * Intent, resulting in the stack now being: A, B.
     *
     * <p>The currently running instance of activity B in the above example will
     * either receive the new intent you are starting here in its
     * onNewIntent() method, or be itself finished and restarted with the
     * new intent.  If it has declared its launch mode to be "multiple" (the
     * default) and you have not set {@link #FLAG_ACTIVITY_SINGLE_TOP} in
     * the same intent, then it will be finished and re-created; for all other
     * launch modes or if {@link #FLAG_ACTIVITY_SINGLE_TOP} is set then this
     * Intent will be delivered to the current instance's onNewIntent().
     *
     * <p>This launch mode can also be used to good effect in conjunction with
     * {@link #FLAG_ACTIVITY_NEW_TASK}: if used to start the root activity
     * of a task, it will bring any currently running instance of that task
     * to the foreground, and then clear it to its root state.  This is
     * especially useful, for example, when launching an activity from the
     * notification manager.
     *
     * <p>See
     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
     * Stack</a> for more information about tasks.
     */

解释很简单,如果intent设置了这个FLAG,假设需要新启动的Activity为B,并且任务栈中已经存在B的实例,那么会将任务栈中B之上的所有Activity(如果存在)结束。此时,任务栈栈顶的Activity为一个接收到了intent信息的B。

举例说明,假设任务栈中有四个Activity,分别为A-B-C-D(栈顶为D)。此时D调用startActivity() 方法去生成B,此时任务栈中的C和D将会被结束,栈顶为接收到了Intent的B。任务栈中剩余的Activity为A-B。

最后上例中B接收intent的方式取决于它的启动模式,当他的启动模式为标准模式时,B会结束自身在重新创建新的实例来接收intent。而其他启动模式,则不会创建新的实例,而是在onNewIntent()方法中接收intent信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值