我希望能够在用户点击给定模式的网址时提示我的应用打开链接,而不是允许浏览器打开它。这可能是用户在浏览器或电子邮件客户端中的网页上,或者在新建应用程序中的WebView中。
例如,点击手机中任意位置的YouTube链接,您将有机会打开YouTube应用。
如何为自己的应用实现这一目标?
答案 0 :(得分:140)
使用类别android.intent.category.BROWSABLE的android.intent.action.VIEW。
来自Romain Guy的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之后,您需要查找操作,然后使用您已下达的网址执行操作。 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),所以你可能会发现有更好的方法可以达到这个目的。
答案 1 :(得分:2)
有些库会自动从url解析参数。
,例如
https://github.com/airbnb/DeepLinkDispatch
&安培;&安培;
https://github.com/mzule/ActivityRouter
后者是我写的。哪个可以解析给定类型的参数,而不是String。
实施例
@Router(value = "main/:id" intExtra = "id")
...
int id = getIntent().getInt("id", 0);
答案 2 :(得分: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;
}
}