从浏览器中截取链接打开我的 Android 应用程序

我希望能够提示我的应用程序打开一个链接时,用户点击一个给定模式的 URL,而不是让浏览器打开它。这可能是当用户在浏览器或电子邮件客户端的一个网页上,或在一个新开发的应用程序的 WebView 中。

例如,在手机的任何地方点击 YouTube 链接,你就有机会打开 YouTube 应用程序。

我如何为自己的应用程序实现这一点?

64843 次浏览

Use an android.intent.action.VIEW of category android.intent.category.BROWSABLE.

From Romain Guy's Photostream app's 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>

Once inside you're in the activity, you need to look for the action, and then do something with the URL you've been handed. The Intent.getData() method gives you a 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);
}
}

It should be noted, however, that this app is getting a little bit out of date (1.2), so you may find there are better ways of achieving this.

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;
}


}

There are some libraries parse parameters from url automatically.

such as

https://github.com/airbnb/DeepLinkDispatch

&&

https://github.com/mzule/ActivityRouter

The later one is wrote by me. Which can parse parameters to given type, not always String.

Example

@Router(value = "main/:id" intExtra = "id")
...
int id = getIntent().getInt("id", 0);