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

先介绍下应用场景, 比如我现在在新闻客户端分享了一篇文章到外部出去,分享出去的页面是个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 可以兼容所有版本.暂时没有研究过, 先 不发表意见, 后期有时间再研究下发个博客.


}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值