簡體   English   中英

onNewIntent()生命周期和已注冊的偵聽器

[英]onNewIntent() lifecycle and registered listeners

我正在使用singleTop Activity通過onNewIntent()從搜索對話框接收意圖。

我注意到在onNewIntent()之前調用onPause() ,然后調用onResume() 視覺:

  • 搜索對話框已啟動
  • 搜索意圖觸發了活動
  • onPause()
  • onNewIntent()
  • onResume()

問題是我在onResume()中注冊了在onPause()中被刪除的偵聽器,但是在onNewIntent()調用中需要它們。 有沒有一種標准方法可以讓這些聽眾可用?

onNewIntent()意味着singleTop活動的入口點已經在堆棧中的其他位置運行,因此無法調用onCreate() 從活動生命周期的角度來看,因此需要在onNewIntent()之前調用onPause() onNewIntent() 我建議你重寫你的活動,不要在onNewIntent()使用這些監聽器。 例如,大多數時候我的onNewIntent()方法看起來像這樣:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

使用getIntent()onResume()發生所有設置邏輯。

注意:從另一個方法調用生命周期方法不是一個好習慣。 在下面的示例中,我試圖實現無論您的Activity類型如何,都將始終調用onNewIntent。

除了第一次創建活動時,OnNewIntent()總是被調用singleTop / Task活動。 那時onCreate被稱為提供解決方案,在這個線程上詢問的幾個查詢。

您可以通過將onNewIntent放入onCreate方法來調用onNewIntent

@Override
public void onCreate(Bundle savedState){
    super.onCreate(savedState);
    onNewIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM