how to avoid handling a deep link twice on android?

4.5k views Asked by At

I have an android test app that handles a custom URL deep link (e.g. myapp://xxx/yyy) inside onResume as follows:

if (intent.getAction() != Intent.ACTION_VIEW) return;
String data = intent.getDataString();
if (data == null) return;
// do stuff with 'data' which is the custom URL

The problem is that this code processes the URL again and again every time the app resumes, even if it wasn't reopened using a deep link! So let's say I:

  1. run the app once using a custom url
  2. the URL gets processed correctly
  3. I move the app to the background again
  4. I reopen the app as usual (not through a deep link, just by pressing its icon)
  5. The URL gets processed again, as getDataString() keeps returning the last URL
  6. If I kill the app process and launch it regularly (not via a link) - only then getDataString() returns null and the URL processing stops.

As per some suggestions, I moved the code to onCreate(). This still runs over and over, for example, when the device rotates even if the app is still in the foreground. So onCreate is also not a good option.

How do I avoid getting the same URL over and over when the app resumes?

3

There are 3 answers

4
Sagi Mann On

Based on the comments above, the solution that works best seems to be:

  1. place the URL processing code inside onCreate(state)
  2. only process the URL if state == null

Code sample:

void onCreate(Bundle savedInstanceState) {
    if (savedInstanceState == null) {
        if (intent.getAction() == Intent.ACTION_VIEW) {
            String data = intent.getDataString();
            if (data != null) {
                // ... process URL in 'data'
            }
        }
    }
}
0
Robert James Whelan On

After processing the intent use setIntent(null);

0
xfdai On

I think you should process the url in OnNewIntent and onCreate(neither will be call when become active from background), to avoid multiple processing when rotating, there are two solutions to me:

Solution 1: In onCreate, ignore it if savedInstanceState is no null, This solution based on multiple calling is from rotation, and only need changes on app side.

Solution 2: Make the deeplink url dynamic, which changes every time(like myapp://xxx/yyy?stamp=xxxx), and you can check if the url is already processed. This solution can take any case, but need you modify the url ( maybe from server side ).