Android應(yīng)用程序組件Activity的"singleTask"(12)
注意,這里我們?cè)O(shè)置MainActivity的taskAffinity屬性值為"shy.luo.task.main.activity",
設(shè)置 SubActivity的taskAffinity屬性值為"shy.luo.task.sub.activity"。
重新編譯一下程序,在模擬器上把這 個(gè)應(yīng)用程序再次跑起來(lái),
用“adb shell dumpsys activity”命令再來(lái)查看一下系統(tǒng)運(yùn)行的的任務(wù),就會(huì)看到:
- [html] view plaincopyRunning activities (most recent first):
- TaskRecord{4069c020 #4 A shy.luo.task.sub.activity}
- Run #2: HistoryRecord{40725040 shy.luo.task/.SubActivity}
- TaskRecord{40695220 #3 A shy.luo.task.main.activity}
- Run #1: HistoryRecord{406b26b8 shy.luo.task/.MainActivity}
- TaskRecord{40599c90 #2 A com.android.launcher}
- Run #0: HistoryRecord{40646628 com.android.launcher/com.android.launcher2.Launcher}
這里就可以看到,SubActivity和MainActivity就分別運(yùn)行在不同的任務(wù)中了。
至此,我們總結(jié)一下,設(shè)置了"singleTask"啟動(dòng)模式的Activity的特點(diǎn):
1. 設(shè)置了"singleTask"啟動(dòng)模式的Activity,它在啟動(dòng)的時(shí)候,會(huì)先在系統(tǒng)中查找屬性值affinity等于它的屬性值 taskAffinity的任務(wù)存在;如果存在這樣的任務(wù),它就會(huì)在這個(gè)任務(wù)中啟動(dòng),否則就會(huì)在新任務(wù)中啟動(dòng)。因此,如果我們想要設(shè)置 了"singleTask"啟動(dòng)模式的Activity在新的任務(wù)中啟動(dòng),就要為它設(shè)置一個(gè)獨(dú)立的taskAffinity屬性值。
2. 如果設(shè)置了"singleTask"啟動(dòng)模式的Activity不是在新的任務(wù)中啟動(dòng)時(shí),它會(huì)在已有的任務(wù)中查看是否已經(jīng)存在相應(yīng)的Activity實(shí) 例,如果存在,就會(huì)把位于這個(gè)Activity實(shí)例上面的Activity全部結(jié)束掉,即最終這個(gè)Activity實(shí)例會(huì)位于任務(wù)的堆棧頂端中。
看來(lái),要解開(kāi)Activity的"singleTask"之謎,還是要自力更生啊,不過(guò),如果我們仔細(xì)閱讀官方文檔,在http://developer.android.com/guide/topics/manifest/activity-element.html中,有這樣的描述:
As shown in the table above, standard is the default mode and is appropriate for most types of activities. SingleTop is also a common and useful launch mode for many types of activities. The other modes — singleTask and singleInstance —are not appropriate for most applications, since they result in an interaction model that is likely to be unfamiliar to users and is very different from most other applications.
Regardless of the launch mode that you choose, make sure to test the usability of the activity during launch and when navigating back to it from other activities and tasks using the BACK key.
這樣看,官方文檔也沒(méi)有坑我們呢,它告誡我們:make sure to test the usability of the activity during launch。