問(wèn)題:項(xiàng)目上遇到個(gè)問(wèn)題,有個(gè) SingleInstance 的 activity Activity-A, 可以看成一個(gè)dialog樣式的list,點(diǎn)擊其中的每個(gè)item可以打開(kāi)對(duì)應(yīng)的詳情界面,即跳轉(zhuǎn)到 Activity-B,跳轉(zhuǎn)到 Activity-B 后仍會(huì)控制讓 Activity-A 再次彈出覆蓋在 Activity-B 之上,可以再次點(diǎn)擊其中的item打開(kāi)新的詳情界面, Activity-B 是個(gè)普通 activity, 預(yù)期是每次點(diǎn)擊 Activity-A 中的item 后會(huì)打開(kāi)一個(gè)新的 Activity-B 來(lái)顯示詳情,多次點(diǎn)擊后應(yīng)該有多個(gè) Activity-B 的實(shí)例,分別顯示不同item的詳情。 然而實(shí)際過(guò)程中發(fā)現(xiàn) Activity-B 始終只有一個(gè)實(shí)例,始終顯示的是最后一次點(diǎn)擊的item的詳情, 即便在startActivity的intent中不添加任何flag也是如此。
原因: 查看官方文檔后發(fā)現(xiàn),從一個(gè) SingleInstance 的 Activity 跳轉(zhuǎn)到別的 Activity 時(shí), 默認(rèn)是加了 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 ,如果目標(biāo) Activity 已經(jīng)存在于一個(gè)task時(shí),不會(huì)創(chuàng)建一個(gè)新的實(shí)例,而是把已有的那個(gè)task帶到前臺(tái), 所以導(dǎo)致了以上問(wèn)題的出現(xiàn)。
“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 里同時(shí)加上 FLAG_ACTIVITY_NEW_TASK 和 FLAG_ACTIVITY_MULTIPLE_TASK (必須同時(shí)使用),官方文檔對(duì)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.
參考官方文檔: