TextView上的ActivityNotFoundException,autoLink =“web”

时间:2014-02-21 15:06:59

标签: android

如果点击ActivityNotFoundException因为它显示网站,如何抓住TextView

如果设备没有浏览器而不是抛出该异常。

XML:

<TextView
    android:id="@+id/tvTextView"
    android:autoLink="web" />

爪哇:

TextView tvTextView = (TextView) findViewById(R.id.tvTextView);
tvTextView.setText("http://www.stackoverflow.com/");

3 个答案:

答案 0 :(得分:4)

您可以使用以下内容检查是否有活动来处理您的意图:

Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.stackoverflow.com"));
PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
if (infos.size() > 0) {
    //At least one application can handle your intent 
    //Put this code in onCreate and only Linkify the TextView from here
    //instead of using android:autoLink="web" in xml
    Linkify.addLinks(tvTextView, Linkify.WEB_URLS);
    // or tvTextView.setAutoLinkMask(Linkify.WEB_URL), as suggested by Little Child
}else{
    //No Application can handle your intent, notify your user if needed
}

答案 1 :(得分:3)

围绕startActivity()区块中的try-catch。就是这样 您的catch将处理ActivityNotFoundException

根据2Dee的回答更新:
应该做的是,不要在XML中使用autoLink:web,OP必须首先创建打开网站的意图,比如谷歌。在onCreate()中,查看是否有Activity来处理它。如果是,请检索TextView并致电setAutoLinkMask(Linkify.WEB_URL)

代码段:

Intent checkBrowser = new Intent(Intent.ACTION_VIEW);
checkBrowser.setData("http://www.grumpycat.com");
List<ResolveInfo> info = context.getPackageManager().queryIntentActivities(checkBrowser,0);
if(info.getSize() > 0){
    TextView  tv = (TextView) findElementById(R.id.tv);
    tv.setAutoLinkMask(Linkify.WEB_URL);
}

答案 2 :(得分:1)

您可以使用此功能检查浏览器是否可用

public boolean isBrowserAvailable(Context c) {

    Intent i = new Intent(Intent.ACTION_VIEW);
        i.setData("http://www.google.com");//or any other "known" url
        List<ResolveInfo> ia = c.getPackageManager().queryIntentActivities(i, 0);
        return (ia.size() > 0);


}

然后,在onCreate中,您决定是否将其设为自动链接。

    if (isBrowserAvailable(this) 

          tvTextView.setAutoLinkMask(Linkify.WEB_URL)