【问题标题】:android.content.ActivityNotFoundException when link does not contain http链接不包含 http 时出现 android.content.ActivityNotFoundException
【发布时间】:2014-10-28 20:19:12
【问题描述】:

我的应用程序允许用户在使用有限的 HTML 时向其他用户键入消息。我允许的其中一件事是使用超链接。

例子:

<a href="www.google.com">Google</a>

我正在通过以下方法填充TextView

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

如果用户创建的超链接没有在 url 前加上 http 前缀,应用程序会崩溃并出现以下异常:

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)

如果网址以http 为前缀,则一切正常。

例子:

<a href="http://www.google.com">Google</a>

如何防止这种情况发生?

【问题讨论】:

    标签: android textview


    【解决方案1】:

    问题是Html.fromHtml() 为嵌入的 URL 创建了URLSpan 实例,并且这个类“盲目地”使用提供的 url 调用 startActivity()。只要 URL 与任何注册的活动不匹配,就会崩溃。

    this CommonsWare post 很好地解释了这个问题。那里的解决方案/示例覆盖onClick() 并处理ActivityNotFoundException 以防止崩溃。

    如果您想要对链接更加宽容,则可以改写getURL(),例如如下:

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

    请注意,这是一个非常粗略的示例(例如,它不考虑“https”链接)——根据需要改进!

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-30
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2013-12-07
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多