您的位置:首页 > 移动开发

H5网页端直接打开APP并获取传递数据的方案.

2017-04-11 14:46 239 查看
先介绍下应用场景, 比如我现在在新闻客户端分享了一篇文章到外部出去,分享出去的页面是个H5页面, 页面中有提示点击 [ 打开app ] 即可打开本地存在的 app , 并且把文章类型与 ID 传递到 app 中让 app 打开这个对应类型与 ID 的新闻页面. 

不废话直接撸代码{

1.首先与H5前端开发同事约定一个scheme值.例如:newsapp
注意要小写,否则会有不能响应的异常!

2.在你的项目清单文件中,在想要响应并打开的activity的注册标签上加入如下所示的意图过滤器.

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>

<data
android:scheme="newsapp" />
</intent-filter>
</activity>
</application>


这里有一点要注意,如果你的启动activity是Main的话, 要像这样加2个过滤器, 否则会产生安装app后没有桌面icon的BUG. 如果不是main而是某一个子页面的activity的话只需要加入上面的第二个意图过滤器就好了.

3. 接下来先看下前端的简单实例代码

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> title </title>
</head>
<body>
<a href="newsapp://TYPE=1&ID=110">open app</a><br/>
</body>
</html>

这个H5页面只有一个 open app 的按钮,点击的时候触发 scheme 通知,此时就会打开你安装在设备中的 app .

4. 获取页面传递过来的值.

我们要在打开的 app 中获取到 H5 传递过来的值需要这么做.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri uri = getIntent().getData();
Log.e("log", uri +" " );
if (uri != null){
String type = uri.getQueryParameter("TYPE");
String id = uri.getQueryParameter("ID");
Log.e("log", type + " = " +  id);
Toast.makeText(this, type + " = " +  id, Toast.LENGTH_SHORT).show();
}
}


5. 这种方案属于比较老的技术, 我参考到的资料是 2013 年的,离现在已经 4 年. 目前据我所知的新技术, 在安卓端有 app link, 是安卓 M ( 6.0 ) 后支持的技术. 但是在网上有资料查到使用 HOKO 可以兼容所有版本.暂时没有研究过, 先 不发表意见, 后期有时间再研究下发个博客.

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐