2009-10-22 92 views
99

我希望能夠在用戶點擊給定模式的URL而不是允許瀏覽器打開它時提示我的應用打開鏈接。這可能是用戶在瀏覽器中的網頁上,電子郵件客戶端中或在新鮮出爐的應用程序中的WebView中。攔截瀏覽器中的鏈接以打開我的Android應用

例如,從手機中的任意位置點擊YouTube鏈接,您就有機會打開YouTube應用。

我該如何實現我自己的應用程序?

回答

136

使用類別android.intent.category.BROWSABLE的android.intent.action.VIEW。

從羅曼蓋伊的Photostream應用程序的AndroidManifest.xml

<activity 
     android:name=".PhotostreamActivity" 
     android:label="@string/application_name"> 

     <!-- ... -->    

     <intent-filter> 
      <action android:name="android.intent.action.VIEW" /> 
      <category android:name="android.intent.category.DEFAULT" /> 
      <category android:name="android.intent.category.BROWSABLE" /> 
      <data android:scheme="http" 
        android:host="flickr.com" 
        android:pathPrefix="/photos/" /> 
      <data android:scheme="http" 
        android:host="www.flickr.com" 
        android:pathPrefix="/photos/" /> 
     </intent-filter> 
    </activity> 

一旦進入你的activity的時候,你需要尋找的動作,然後做你已經交到URL的東西。 Intent.getData()方法給你一個Uri。

final Intent intent = getIntent(); 
    final String action = intent.getAction(); 

    if (Intent.ACTION_VIEW.equals(action)) { 
     final List<String> segments = intent.getData().getPathSegments(); 
     if (segments.size() > 1) { 
      mUsername = segments.get(1); 
     } 
    } 

應當注意的是,這個應用程序是越來越有點過時(1.2)的,所以你會發現有實現這一目標的更好的方法。

+8

有一點要注意的 - 您的用戶將使用合適的應用程序,因爲所有你做的是應用程序註冊你的處理器的選擇呈現。個人(作爲用戶)我很惱火,但我意識到我可以選擇「默認操作」 – Bostone 2009-10-22 22:25:17

+1

這不適用於HTC手機。我如何使它在HTC手機上工作? – user484691 2012-09-18 18:39:36

+57

如果您關心包含查詢字符串的完整URL,您可能會想要使用intent.getDataString()而不是getData()。這個評論會節省你花費我的時間..... :-( – 2012-10-30 13:26:11

0
private class MyWebViewClient extends WebViewClient { 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     setUrlparams(url); 

     if (url.indexOf("pattern") != -1) { 
      // do something 
      return false; 
     } else { 
      view.loadUrl(url); 
     } 

     return true; 
    } 

} 
+4

謝謝。在你擁有webview的情況下,這很有用。我問的問題是如何獲取我的應用程序攔截任何應用中鏈接的點擊(例如,瀏覽器)。 – jamesh 2010-01-17 01:21:35

相關問題