今天在项目中接触到了这么一个关键字,记录下来以备以后查看。
首先来看代码:
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信息。