问题
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:
- run the app once using a custom url
- the URL gets processed correctly
- I move the app to the background again
- I reopen the app as usual (not through a deep link, just by pressing its icon)
- The URL gets processed again, as getDataString() keeps returning the last URL
- 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:
- place the URL processing code inside onCreate(state)
- 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