Android StartActivies(Intent[] intents)用法

_小馬快跑_發表於2017-12-15
startActivities
void startActivities ([Intent[] intents, Bundle options)
    Launch multiple new activities. This is generally the same as calling [startActivity(Intent)])
for the first Intent in the array, that activity during its creation calling [startActivity(Intent)]
for the second entry, etc. Note that unlike that approach, generally none of the activities except the last in the array will be created at this point, but rather will be created when the user first visits them (due to pressing back from the activity on top).
This method throws [ActivityNotFoundException]
if there was no Activity found for *any* given Intent. In this case the state of the activity stack is undefined (some Intents in the list may be on it, some not), so you probably want to avoid such situations.
複製程式碼

啟動多個新的activity,通常和我們呼叫startActivity(Intent)是一樣的,但最開始建立的不是第一個Activity而是最後一個Activity,當按返回鍵後,會發現返回順序和Intent[] intents中的順序正好是相反的。

來,舉個例子:

Intent[] intents = new Intent[3];
intents[0] = new Intent(MainActivity.this, Activity1.class);
intents[1] = new Intent(MainActivity.this, Activity2.class);
intents[2] = new Intent(MainActivity.this, Activity3.class);
startActivities(intents);
複製程式碼

執行之後首先跳轉的是Activity3,按返回鍵後跳轉到了Activity2,再按返回鍵跳轉到了Activity1,正好和我們Intent[] intents陣列中的順序是相反的,最後看下Log日誌:

09-18 14:49:22.976 3116-3116 E/TTT: Activity3 onCreate
09-18 14:49:22.976 3116-3116 E/TTT: Activity3 onStart
09-18 14:49:22.976 3116-3116 E/TTT: Activity3 onResume
09-18 14:49:25.456 3116-3116 E/TTT: Activity2 onCreate
09-18 14:49:25.456 3116-3116 E/TTT: Activity2 onStart
09-18 14:49:25.461 3116-3116 E/TTT: Activity2 onResume
09-18 14:49:26.771 3116-3116 E/TTT: Activity1 onCreate
09-18 14:49:26.771 3116-3116 E/TTT: Activity1 onStart
09-18 14:49:26.771 3116-3116 E/TTT: Activity1 onResume
複製程式碼

我們專案中是在推送訊息的時候會用到StartActivies(Intent[] intents),

Intent[] intents = new Intent[2];
intents[0] = new Intent(context, GuideAct.class);
intents[0].addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intents[1] = new Intent(context, Target.class);
//應用在前臺,直接startActivity(intents[1]),否則跳轉的是startActivities(intents)
if (Constant.isAppOpen) {    
context.startActivity(intents[1]);
} else {    
context.startActivities(intents);
}
複製程式碼

這樣就可以實現當使用者從推送訊息中點進目標Activity並按返回鍵後,重新啟動應用!

相關文章