网页打开Android APP

原理解析

在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...

欢迎评论

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12505749.html