网页打开Android APP

原理解析

在Android平台而言,URI主要分三个部分:
scheme,authority,path
其中authority又分为host和port。格式以下:html

<scheme>://<host>:<port>[<path>|<pathPrefix>|<pathPattern>]

对应的manifest中的<data>配置以下:android

<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均无效!web

咱们最经常使用的是scheme,host,port,path这四个配置。api

实现方法

首先在AndroidManifest中的MainActivity中添加一个<intent-filter>:app

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

而后在你的网页中添加一个连接:dom

<a href="protocol://domain/link>打开app</a>

最后,点击这个a连接,若是app成功弹出,那么恭喜你,你成功了。ide

拓展

光打开app可能还不够,有时咱们要传递数据,那么怎么去传递数据呢?url

咱们能够使用上面的方法,把一些数据传给app,那么先修改一下连接:code

<a href="protocol://domain/link?id=123>打开app并传递id</a>

而后在app上的MainActivity中的onCreate方法中添加代码:htm

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

欢迎评论

相关文章
相关标签/搜索