Android應用程序組件Activity的"singleTask"(12)
注意,這里我們設置MainActivity的taskAffinity屬性值為"shy.luo.task.main.activity",
設置 SubActivity的taskAffinity屬性值為"shy.luo.task.sub.activity"。
重新編譯一下程序,在模擬器上把這 個應用程序再次跑起來,
用“adb shell dumpsys activity”命令再來查看一下系統運行的的任務,就會看到:
- [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就分別運行在不同的任務中了。
至此,我們總結一下,設置了"singleTask"啟動模式的Activity的特點:
1. 設置了"singleTask"啟動模式的Activity,它在啟動的時候,會先在系統中查找屬性值affinity等于它的屬性值 taskAffinity的任務存在;如果存在這樣的任務,它就會在這個任務中啟動,否則就會在新任務中啟動。因此,如果我們想要設置 了"singleTask"啟動模式的Activity在新的任務中啟動,就要為它設置一個獨立的taskAffinity屬性值。
2. 如果設置了"singleTask"啟動模式的Activity不是在新的任務中啟動時,它會在已有的任務中查看是否已經存在相應的Activity實 例,如果存在,就會把位于這個Activity實例上面的Activity全部結束掉,即最終這個Activity實例會位于任務的堆棧頂端中。
看來,要解開Activity的"singleTask"之謎,還是要自力更生啊,不過,如果我們仔細閱讀官方文檔,在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.
這樣看,官方文檔也沒有坑我們呢,它告誡我們:make sure to test the usability of the activity during launch。