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

编程知识 更新时间:2023-05-02 19:46:34

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


}

更多推荐

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

本文发布于:2023-04-28 09:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/67aa2c867580dd3f54c466b3981bd0d0.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网页   方案   数据   APP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 108256文章数
  • 27372阅读数
  • 0评论数