在官方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. |
---|
在該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方法,然後再執行生命週期的其他方法.
文章出自: https://www.cnblogs.com/zawn/archive/2012/10/23/2735875.html