Fat Monk
Fat Monk

Reputation: 2265

Where should I be using getIntent() in the Android lifecycle

I have a bug in my app which I thought I knew how to resolve, but now I've thought more about what is happening I'm not sure I do know the fix.

My app receives an incoming intent from a calling third party app as a string. That string can be sent as a SEND intent or a VIEW intent.

All of that works fine unless the app is already running...

This is what is happening:

  1. My app is not running (not listed in the running apps view)
  2. Share is clicked in another (third party) app and my app is selected to receive the shared text (text1).
  3. My app opens and the text is displayed (and processed) as expected.
  4. The user switches back to the third party app and shares some different text (text2) and my app is selected to receive this new text.
  5. My app opens, but the original text (text1) is still displayed.

At this point I thought that the bug was because I am reading the intent in onCreate() and then displaying and processing it. My thinking was that as the app is already running onCreate() is not being called when the app is shown the second time as we jump into the lifecycle at onResume().

However, if I continue the test as follows:

  1. Without exiting my app the user switches back to the third party app again and again shares the same piece of second text (text2) with my app.
  2. My app is displayed again but this time correctly shows and processes the second text.

How can this be, as the app is still running, surely onCreate() is still not going to be called!

I thought that the fix was going to be simply to move the getIntent() call into onResume() (or onStart() ?) But now I'm not sure about this. Is this right thing to do?

Upvotes: 1

Views: 511

Answers (1)

codeFood
codeFood

Reputation: 1251

The core of the issue is the fact that your Activity is already on top of the activity stack when the second Intent is being fired.

The launch mode will matter here.

What you can do is, set the launchMode to singleTop, and then get the intent in onNewIntent() method.

That is a good way of handling such scenarios. Please read the link above and it will make things very clear.

Upvotes: 1

Related Questions