如何避免在Android上处理两次深层链接? [英] how to avoid handling a deep link twice on android?

查看:103
本文介绍了如何避免在Android上处理两次深层链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android测试应用程序,它处理onResume内部的自定义URL深度链接(例如myapp:// xxx / yyy),如下所示:

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

问题是即使未使用深层链接重新打开,此代码也会在每次应用恢复时一次又一次地处理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. 使用自定义网址运行应用一次

  2. 已处理了网址正确

  3. 我再次将应用移至后台

  4. 我照常打开了该应用(不是通过深层链接,只需按其图标即可)

  5. 由于getDataString()不断返回最后一个URL,URL被再次处理

  6. 如果我终止了应用程序进程并定期启动它(不是通过链接)-只有这样,getDataString()返回null并停止URL处理。

  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.

根据一些建议,我将代码移到了onCreate()。例如,即使应用仍然在前台,当设备旋转时,它仍然会反复运行。因此,onCreate也不是一个好选择。

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.

如何避免在应用恢复时重复获取相同的URL?

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

推荐答案

根据上述评论,最有效的解决方案似乎是:

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


  1. 将URL处理代码放在onCreate(state)内

  2. 仅在state == null时处理URL

代码示例:

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

这篇关于如何避免在Android上处理两次深层链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆