android.content.ActivityNotFoundException当链接不包含HTTP不包含、链接、content、android

2023-09-07 12:14:58 作者:作业什么的都去死吧

我的应用程序允许用户在使用有限的HTML邮件类型给其他用户。其中一件事我允许是利用超链接。

My app allows users to type messages to other users while using limited HTML. One of the things I allow is the use of hyperlinks.

例如:

< A HREF =www.google.com>谷歌< / A>

我填充的TextView 通过下面的方法:

I am populating the TextView via the following method:

txtview.setMovementMethod(LinkMovementMethod.getInstance());
txtview.setText(Html.fromHtml(items.get(position).getBody()));

如果用户创建无prefixing超链接 HTTP 的url,但以下情况除外应用程序崩溃:

If the user creates a hyperlink without prefixing http to the url, the application crashes with the following exception:

FATAL EXCEPTION: main
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=www.google.com (has extras) }
    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1545)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1416)

如果该URL pfixed与 HTTP $ P $,一切工作正常。

If the url is prefixed with http, everything works fine.

例如:

< A HREF =htt​​p://www.google.com>谷歌< / A>

我怎么能发生prevent呢?

How can I prevent this from happening?

推荐答案

问题是, Html.fromHtml()创建的 URLSpan 以嵌入的URL实例,该类盲目地调用 startActivity()与所提供的URL。这种崩溃只要URL不与任何已注册的活动相匹配。

The problem is that Html.fromHtml() creates URLSpan instances for embedded URLs, and this class "blindly" calls startActivity() with the supplied url. This crashes whenever the URL does not match with any registered activity.

这个问题是很好的这CommonsWare帖子。该解决方案/例如,有覆盖的onClick()并处理 ActivityNotFoundException 来prevent崩溃。

The problem is well explained in this CommonsWare post. The solution/example there overrides onClick() and handles the ActivityNotFoundException to prevent the crash.

如果你想要做的是更宽松的有关链接相反,你可以覆盖的getURL()相反,举例如下:

If what you want to do is to be more permissive about the link instead, you could override getURL() instead, for example as follows:

    @Override
    public String getURL()
    {
        String url = super.getURL();
        if (!url.toLowerCase().startsWith("http"))
            url = "http://" + url;

        return url;
    }

请注意,这一个的非常的原油例子(例如,它不占https开头的链接) - 在需要改善

Note that this a very crude example (e.g. it does not account for "https" links) -- improve as needed!