版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z_x_Qiang/article/details/88694705
实现原理
首先我们来看一下网页跳转到应用的实现原理
在Android平台而言,URI主要分三个部分:scheme, authority, path, queryString。其中authority又分为host和port。格式如下:
scheme://host:port/path?qureyParameter=queryString
在Android的Manifest配置文件中,<intent-filter>
配置项中有<data>
配置
其中<data>
包含内容有:
<data android:host=""
android:mimeType=""
android:path=""
android:pathPattern=""
android:pathPrefix=""
android:port=""
android:scheme=""
android:ssp=""
android:sspPattern=""
android:sspPrefix=""/>
通过配置<data>
可以对网页进行过滤,符合匹配条件的网页才跳转到应用。一般只需要设置host
和scheme
即可。
实现:
1. 配置 intent-filter
AndroidManifest.xml
<activity android:name=".MainActivity">
<!-- 需要添加下面的intent-filter配置 -->
<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:host="myhost"
android:path="/main"
android:port="1024"
android:scheme="myscheme" />
</intent-filter>
</activity>
2.测试网页
main 下新建 assets 文件,写了简单的 Html 网页用于 WebView 展示,来进行测试。
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>这是一个 WebView</h1>
<a href="market://details?id=com.tencent.mm">open app with market</a>
<br/>
<a href="myscheme://myhost:1024/main?key1=value1&key2=value2">open app with Uri Scheme</a>
<br/>
</body>
</html>
加载html页面
webView.loadUrl("file:///android_asset/index.html");
3.在activity中获取参数
Intent intent = getIntent();
if (null != intent && null != intent.getData()) {
// uri 就相当于 web 页面中的链接
Uri uri = intent.getData();
Log.e(TAG, "uri=" +uri);
String scheme = uri.getScheme();
String host = uri.getHost();
int port = uri.getPort();
String path = uri.getPath();
String key1 = uri.getQueryParameter("key1");
String key2 = uri.getQueryParameter("key2");
Log.e(TAG, "scheme=" + scheme + ",host=" + host
+ ",port=" + port + ",path=" + path
+ ",query=" + uri.getQuery()
+ ",key1=" + key1 + ",key2=" + key2);
}