在官方API上的說明如下:
http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent):
protected void onNewIntent (Intent intent)
This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP
flag when callingstartActivity(Intent)
. In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.
An activity will always be paused before receiving a new intent, so you can count on onResume()
being called after this method.
Note that getIntent()
still returns the original Intent. You can use setIntent(Intent)
to update it to this new Intent.
Parameters
intent | The new intent that was started for the activity. |
---|
See Also
Activity 的 onNewIntent方法的調用可總結如下:
在該Activity的實例已經存在於Task和Back stack中(或者通俗的說可以通過按返回鍵返回到該Activity )時,當使用intent來再次啟動該Activity的時候,如果此次啟動不創建該Activity的新實例,則系統會調用原有實例的onNewIntent()
方法來處理此intent.
且在下面情況下系統不會創建該Activity的新實例:
1,如果該Activity在Manifest中的android:launchMode定義
為singleTask
或者singleInstance
.
2,如果該Activity在Manifest中的android:launchMode定義
為singleTop
且該實例位於Back stack的棧頂.
3,如果該Activity在Manifest中的
,且上述intent包含Intent.android:launchMode定義
為singleTop
FLAG_ACTIVITY_CLEAR_TOP
標志.
4,如果上述intent中包含 Intent.FLAG_ACTIVITY_CLEAR_TOP
標志和且包含 Intent.FLAG_ACTIVITY_SINGLE_TOP
標志.
5,如果上述intent中包含 Intent.
標志且FLAG_ACTIVITY_SINGLE_TOP
該實例位於Back stack的棧頂.
上述情況滿足其一,則系統將不會創建該Activity的新實例.
根據現有實例所處的狀態不同onNewIntent()
方法的調用時機也不同,總的說如果系統調用onNewIntent()
方法則系統會在onResume()
方法執行之前調用它.這也是官方API為什么只說"you can count on onResume()
being called after this method",而不具體說明調用時機的原因.
下面是不同狀態下調用onNewIntent()
的日志以供參考:
1,如果實例已經被系統kill掉:
10-23 14:03:21.623: D/MainActivity(25990): onCreate 10-23 14:03:21.743: D/MainActivity(25990): onStart 10-23 14:03:21.743: D/MainActivity(25990): onRestoreInstanceState 10-23 14:03:21.743: D/MainActivity(25990): onNewIntent 10-23 14:03:21.753: D/MainActivity(25990): onResume
2,如果實例已被stop:
10-23 12:08:32.063: D/MainActivity(15188): onNewIntent 10-23 12:08:32.063: D/MainActivity(15188): onRestart 10-23 12:08:32.063: D/MainActivity(15188): onStart 10-23 12:08:32.063: D/MainActivity(15188): onResume
3,如果實例已被pause:
10-23 13:47:08.393: D/MainActivity(25672): onNewIntent 10-23 13:47:08.393: D/MainActivity(25672): onResume
第2,3可以總結為如果實例沒有被Kill則會首先執行onNewIntent方法,然后再執行生命周期的其他方法.