关于启动模式之IntentFlag
先来一个简单的例子:
public class MainActivity extends Activity { private Button move; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.e("test", "MainActivity task id is " + getTaskId()); move= (Button) findViewById(R.id.move); move.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this,SecondActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); } } public class SecondActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Log.e("test", "SecondActivity task id is "+getTaskId()); } }
打印结果为:
12-22 13:51:21.128 28827-28827/com.example.god.flagtest E/test﹕ MainActivity task id is 5565
12-22 13:51:21.302 28827-28861/com.example.god.flagtest E/GED﹕ Failed to get GED Log Buf, err(0)
12-22 13:51:32.432 28827-28827/com.example.god.flagtest E/test﹕ SecondActivity task id is 5565
为什么还是同一个task呢?由第二张图可以看到目标activity即secondActivity由于没有设置(亲和力)Affinity属性值,所以,默认secondActivity的Affinity属性值为默认的包名,和MainActivity亲和力一样,所以不会创建一个新的task,要想创建新的task,只要在SecondActivity修改下亲和力值就行,例如
<activity android:name=".SecondActivity" android:taskAffinity="flag.newtask.test" />
现在看看结果:
12-22 14:02:43.328 528-528/com.example.god.flagtest E/test﹕ MainActivity task id is 5566
12-22 14:02:43.680 528-636/com.example.god.flagtest E/GED﹕ Failed to get GED Log Buf, err(0)
12-22 14:02:46.406 528-528/com.example.god.flagtest E/test﹕ SecondActivity task id is 5567
可见新建了一个task
捋一下:android会根据 taskAffinity的名称来查找是否具有相同名称的task,如果有,就将目标activity压入task中,如果没有就新建,如图2
至于FLAG_ACTIVITY_SINGLE_TOP类似于LaunchMode中的Single_Top,两者的作用是类似的,暂不多说
同理还有FLAG_ACTIVITY_CLEAR_TOP,类似于LaunchMode中的Single_Task
最后一种Flag,翻译过来就是重新排序,拿到栈顶,跟FLAG_ACTIVITY_CLEAR_TOP区别在于,它不会把其他实例清除
例子如下:
--
--
ThirdActivity ->(onclick)->SecondActivity ===> SecondActivity
SecondActivity ThirdActivity
FirstActivity FirstActivity