android.content.ActivityNotFoundException当链接不包含http时

And*_*rew 4 android textview

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

例:

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

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

txtview.setMovementMethod(LinkMovementMethod.getInstance());
txtview.setText(Html.fromHtml(items.get(position).getBody()));
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

如果网址带有前缀http,一切正常.

例:

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

我怎样才能防止这种情况发生?

mat*_*ash 8

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

这个CommonsWare帖子很好地解释了这个问题.其中的解决方案/示例覆盖onClick()并处理ActivityNotFoundException以防止崩溃.

如果您想要做的是对链接更加宽容,您可以改写getURL(),例如,如下所示:

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

        return url;
    }
Run Code Online (Sandbox Code Playgroud)

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