問題:項目上遇到個問題,有個 SingleInstance 的 activity Activity-A, 可以看成一個dialog樣式的list,點擊其中的每個item可以打開對應的詳情界面,即跳轉到 Activity-B,跳轉到 Activity-B 后仍會控制讓 Activity-A 再次彈出覆蓋在 Activity-B 之上,可以再次點擊其中的item打開新的詳情界面, Activity-B 是個普通 activity, 預期是每次點擊 Activity-A 中的item 后會打開一個新的 Activity-B 來顯示詳情,多次點擊后應該有多個 Activity-B 的實例,分別顯示不同item的詳情。 然而實際過程中發現 Activity-B 始終只有一個實例,始終顯示的是最后一次點擊的item的詳情, 即便在startActivity的intent中不添加任何flag也是如此。
原因: 查看官方文檔后發現,從一個 SingleInstance 的 Activity 跳轉到別的 Activity 時, 默認是加了 FLAG_ACTIVITY_NEW_TASK 的。
A "singleInstance" activity, on the other hand, permits no other activities to be part of its task. It's the only activity in the task. If it starts another activity, that activity is assigned to a different task — as if FLAG_ACTIVITY_NEW_TASK was in the intent.
而如果添加了 FLAG_ACTIVITY_NEW_TASK ,如果目標 Activity 已經存在于一個task時,不會創建一個新的實例,而是把已有的那個task帶到前臺, 所以導致了以上問題的出現。
“Start the activity in a new task. If a task is already running for the activity you are now starting, that task is brought to the foreground with its last state restored and the activity receives the new intent in onNewIntent().”
解決辦法:在 startActivity 的 intent 里同時加上 FLAG_ACTIVITY_NEW_TASK 和 FLAG_ACTIVITY_MULTIPLE_TASK (必須同時使用),官方文檔對FLAG_ACTIVITY_MULTIPLE_TASK 的解釋是:
Used in conjunction with FLAG_ACTIVITY_NEW_TASK to disable the behavior of bringing an existing task to the foreground. When set, a new task is always started to host the Activity for the Intent, regardless of whether there is already an existing task running the same thing.
參考官方文檔: