Html网页调用本地安卓app

前言

为了保证APP的用户流量,我们会希望用户通过我们分享的文章中通过点击调用我们的APP打开,其实实现起来非常简单。

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

<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>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!--主要是这个配置-->
<data android:scheme="qgyxnews" />
</intent-filter>
</activity>
</application>

</manifest>

Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mTextView = (TextView) findViewById(R.id.tv_main_show);
Intent intent = getIntent();
Uri uri = intent.getData();
if (uri != null) {
String name = uri.getQueryParameter("name");
String scheme = uri.getScheme();
String host = uri.getHost();
String port = uri.getPort() + "";
String path = uri.getPath();
String query = uri.getQuery();
mTextView.setText("获得的数据name:" + name + "\n"
+ "scheme:" + scheme + "\n"
+ "host:" + "host:" + host + "\n"
+ "port:" + port + "\n"
+ "path:" + path + "\n"
+ "query:" + query);
}
}
}

Html代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<meta charset="UTF-8">
<body>
<h1>webToApp</h1>
<a id="linkToCart" href="#">点我打开</a>
</body>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//点击链接的时候调用
$("#linkToCart").click(function(){
//设置linkToCart的href的值
$("#linkToCart").attr("href","qgyxnews://psvmc.cn:8080/mypath?id="+123);
});
});
</script>
</html>