原理解析
在Android平臺而言,URI主要分三個部分:
scheme,authority,path
其中authority又分為host和port。格式如下:
<scheme>://<host>:<port>[<path>|<pathPrefix>|<pathPattern>]
對應的manifest中的<data>
配置如下:
<data android:host=""
android:mimeType=""
android:path=""
android:pathPattern=""
android:pathPrefix=""
android:port=""
android:scheme=""
android:ssp=""
android:sspPattern=""
android:sspPrefix=""/>
其中scheme為必須參數,若沒有指定,那其它的屬性均無效!
如果host沒有指定,那么port,path,pathPrefix,pathPattern均無效!
我們最常用的是scheme
,host
,port
,path
這四個配置。
實現方法
首先在AndroidManifest
中的MainActivity
中添加一個<intent-filter>
:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="protocol" android:host="domain" android:pathPrefix="/link" />
</intent-filter>
然后在你的網頁中添加一個鏈接:
<a href="protocol://domain/link>打開app</a>
最后,點擊這個a鏈接,如果app成功彈出,那么恭喜你,你成功了。
拓展
光打開app可能還不夠,有時我們要傳遞數據,那么怎么去傳遞數據呢?
我們可以使用上面的方法,把一些數據傳給app,那么先修改一下鏈接:
<a href="protocol://domain/link?id=123>打開app并傳遞id</a>
然后在app上的MainActivity中的onCreate方法中添加代碼:
Uri uri = getIntent().getData();
String id= uri.getQueryParameter("id");
這樣就可以傳遞數據啦!
如果用的是應用內的webview,獲取數據的操作為:
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri=Uri.parse(url);
if(uri.getScheme().equals("protocol")&&uri.getHost().equals("domain")){
String id = uri.getQueryParameter("id");
}else{
view.loadUrl(url);
}
return true;
}
});
API
getScheme(); //獲得Scheme名稱
getDataString(); //獲得Uri全部路徑
getHost(); //獲得host
附上uri的官方api鏈接
https://developer.android.com/reference/android/net/Uri.html