how to avoid handling a deep link twice on android?

戏子无情 提交于 2019-12-24 06:46:04

问题


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?


回答1:


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'
            }
        }
    }
}



回答2:


After processing the intent use setIntent(null);




回答3:


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 ).



来源:https://stackoverflow.com/questions/30997662/how-to-avoid-handling-a-deep-link-twice-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!