2014-02-21 72 views
4

如果TextView因爲顯示網站而被點擊,如何捕獲ActivityNotFoundException帶有autoLink =「web」的TextView上的ActivityNotFoundException

如果設備沒有瀏覽器而不是拋出該異常。

XML:

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

的Java:

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

回答

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

如果一個'intent'可以由OP創建,那麼'startActivity()'可以被try-catch包圍。 :) OP說,這是超出他的控制。 :) –

+0

@LittleChild你是絕對正確的!回答編輯;-) – 2Dee

+0

必須使用'Linkify.WEB_URLS',AFAIK。 :),在'onCreate()' –

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); 
} 
+1

不能,它自己處理它,我不叫任何東西,我只設置文本。 – Houssni

+0

+1,'setAutoLinkMask()'聽起來是一個很好的解決方案 – Houssni

+0

+ setAutoLinkMask! – 2Dee

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) 
相關問題