每天進步一點點之Android基礎(3)—— Activity的onNewIntent

onNewIntent() 的觸發時間:

  • 如圖所示,onCreate() 和 onNewIntent() 不會被同時調用。

如果在 AndroidManifest.xml 中,將 Activity 的 launchMode 設置成了 "singleTop" 模式,或者在調用 startActivity(Intent) 時,設置了FLAG_ACTIVITY_SINGLE_TOP 標識,那麼,當該 Activity 再次被啓動時,如果它依然存在於 Activity 棧中,並且剛好處於棧的最頂層時,那麼它將不會被重新創建,而是直接使用原來的實例,此時,onNewIntent(Intent) 將會被調用,後續生命週期中的其它方法,就可以使用 onNewIntent(Intent) 傳遞過來的新的 Intent 參數了。(也就是說,其它方法可以使用更新後的 Intent 參數)

也就是說,調用順序如下:
onNewIntent() -> onRestart() -> onStart() -> onResume()

需要特別注意的是, 如果在 onNewIntent(Intent) 中,不調用 setIntent(Intent) 方法對 Intent 進行更新的話,那麼之後在調用 getIntent() 方法時得到的依然是最初的值。

protected void onNewIntent(Intent intent) {
 
    super.onNewIntent(intent);
 
    setIntent(intent);//must store the new intent unless getIntent() will return the old one
 
    processExtraData();
 
}

在啓動 Activtiy 時,如果希望在 onCreate() 不被觸發的的情況下,依然可以對 Intent 進行操作,這就需要使用 onNewIntent()。
不要忘記,系統可能會隨時殺掉後臺運行的Activity,如果這一切發生,那麼系統就會調用onCreate方法,而不調用onNewIntent方法,一個好的解決方法就是在onCreate和onNewIntent方法中調用同一個處理數據的方法.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章