Html中通过JS脚本启动Android应用

本文最后更新于:2025年8月11日 下午

Html中通过JS脚本启动Android应用

参考链接

通过网页的JS代码启动移动APP

通过Html网页调用本地安卓(android)app程序代码

一、启动你的APP

首先,现在你的APP的Manifest.xml 文件中配置你想提供给js调用的链接

将以下代码添加到你想启动的activity

1
2
3
4
5
6
7
8
9
10
<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="test.app.com"
android:pathPrefix="/a"
android:scheme="mypackage" />
</intent-filter>

如上所示,则提供的链接为: mypackage://test.app.com/a ,其中 pathPrefix
属性是可选项,不使用时,js调用链接就不需要写后面的路径。 接下来是网页中的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Open APP</title>
</head>

<!-- 链接形式 -->
<body>
<a href="mypackage://test.app.com/a">打开app</a><br/>
</body>

<!-- 脚本形式 -->
<script>
window.location.href = "mypackage://test.app.com/a";
</script>
</html>

上面代码中的两种形式,按需求使用其中的一种即可,主要目的就是要打开你的APP Manifest.xml 文件中配置的自定义路径。

二、启动APP同时传入参数

只能打开就没什么意思了,最重要的是,我们要传递数据时,怎么去传递数据呢? 我们可通过链接参数的形式将参数传入到APP中,如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Open APP</title>
</head>

<!-- 链接形式 -->
<body>
<a href="mypackage://test.app.com/a?username=master&passwd=root">打开app</a><br/>
</body>

<!-- 脚本形式 -->
<script>
window.location.href = "mypackage://test.app.com/a?username=master&passwd=root";
</script>
</html>

如果你是通过浏览器打开的,那么可以在 onCreate 或者 onResume 中添加以下代码:

1
2
3
Uri uri = getIntent().getData();
String name= uri.getQueryParameter("username");
String pass= uri.getQueryParameter("passwd");

如果是通过WebView加载的,那么只要获取到 Url 地址的字符串即可:

1
2
3
4
5
6
7
Uri uri=Uri.parse(url);
if (uri.getScheme().equals("mypackage")&&uri.getHost().equals("test.app.com")) {
String arg0=uri.getQueryParameter("username");
String arg1=uri.getQueryParameter("passwd");
} else {
view.loadUrl(url);
}

以上就是 Html中通过JS脚本启动Android应用 的方法。


Html中通过JS脚本启动Android应用
https://blog.doracoin.cc/posts/development/36445.html
作者
Doracoin
发布于
2017年8月31日
更新于
2025年8月11日
许可协议