onNewIntent() lifecycle and registered listeners

AndroidAndroid IntentLifecycle

Android Problem Overview


I'm using a singleTop Activity to receive intents from a search-dialog via onNewIntent().

What I noticed is that onPause() is called before onNewIntent(), and then afterwards it calls onResume(). Visually:

  • search dialog initiated
  • search intent fired to activity
  • onPause()
  • onNewIntent()
  • onResume()

The problem is that I have listeners registered in onResume() that get removed in onPause(), but they are needed inside of the onNewIntent() call. Is there a standard way to make those listeners available?

Android Solutions


Solution 1 - Android

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

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

With all setup logic happening in onResume() by utilizing getIntent().

Solution 2 - Android

Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.

OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.

You can invoke onNewIntent always by putting it into onCreate method like

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDJayCView Question on Stackoverflow
Solution 1 - AndroidRodjaView Answer on Stackoverflow
Solution 2 - AndroidPawan MaheshwariView Answer on Stackoverflow