Android Html交互<一> 网页链接打开本地App
@(Android系统源码解析)[Android, html]
声明:转载请注明出处,知识有限,如有错误,请多多交流指正!
- Android Html交互一 网页链接打开本地App
-
- 效果图
- 网页Html端代码
- Android端代码
-
功能:通过点击网页中的链接,打开手机中的app,获取打开app某一个界面
代码下载地址: https://github.com/app-demo/AndroidHtml.git
效果图
代码主要分为2部分Android和Html代码,为了方便测试将
index_app.html
放在App项目
assets
文件夹下面,再通过
WebView
加载页面,效果图如下:
结果:
网页Html端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>通过点击网页链接打开App</title>
</head>
<body>
<p>通过点击网页链接打开App并且传递数据</p>
<a href="http://www.baidu.com?params=张三">打开app页面(http://www.baidu.com?params=张三)</a>
<br><br><br>
<a href="app://AndroidHtml?params=zhangsan">打开app页面(app://AndroidHtml?params=zhangsan)</a>
<br>
</body>
</html>
Android端代码
- 为了模拟方便,在Activity加载网页:
- 接收到端页面需要在代码xml中注册代码
<activity
android:name=".openapp.AppActivityActivity"
android:label="@string/title_activity_app">
<!--第一种方式:自定义-->
<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="AndroidHtml"
android:scheme="app" />
</intent-filter>
<!--第二种方式:以http协议-->
<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="www.baidu.com"
android:scheme="http" />
</intent-filter>
<!-- 2个方式选择一种就可以了-->
</activity>
主要代码就是通过
data
中host和scheme匹配到链接中的url
<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="AndroidHtml"
android:scheme="app" />
</intent-filter>
- 接收端收到数据的方式通过Intent
public class AppActivityActivity extends AppCompatActivity {
public static final String TAG = "AppActivityActivity";
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app);
textView = (TextView) findViewById(R.id.text);
Intent intent = getIntent();
String scheme = intent.getScheme();
Uri uri = intent.getData();
if (uri != null) {
String host = uri.getHost();
String path = uri.getPath();
String encodedPath = uri.getEncodedPath();
String queryString = uri.getQuery();
// 链接所有数据
String dataString = intent.getDataString();
// 获取链接所携带的参数数据
String params = uri.getQueryParameter("params");
}
}
}
同理只要在app端设置接收端代码就可以通过html打开本地app