这篇文章主要阐述3个知识点(安卓APP 怎么用webview加载H5,H5怎么调用安卓定义的方法,安卓怎么调用H5定义的方法)。
安卓端定义个webview xml 页面,代码如下所示:
- "1.0" encoding="utf-8"?>
- <WebView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/web_view_id"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- WebView>
之后再对webview 实例进行设置,用loadUrl 方法加载H5 路径即可。代码如下:
- webView = (WebView) view.findViewById(R.id.web_view_id);
- WebSettings settings = webView.getSettings();
- settings.setJavaScriptEnabled(true);
-
- WebChromeClient webChromeClient = new WebChromeClient();
- webView.setWebChromeClient(webChromeClient);
-
- settings.setUseWideViewPort(true);
- settings.setLoadWithOverviewMode(true);
- settings.setBuiltInZoomControls(true);
- settings.setSupportZoom(true);
- settings.setDefaultTextEncodingName("UTF-8");
- settings.setJavaScriptCanOpenWindowsAutomatically(true);
-
- //String _url = "http://xxx.xxx.xxx/link/index.html#/home/index"; //服务器地址
- String _url = "file:android_asset/dist/index.html#/home/index"; //本地地址
- webView.loadUrl(_url);
不出意外的话会看到加载的H5页面了。
首先定义一个类,写上供H5调用的方法,注意这个方法要用@JavascriptInterface修饰,代码如下所示:
- public class Mine {
- private Context context;
- public Mine(Context _context){
- this.context = _context;
- }
- @JavascriptInterface
- public void loginOut(){
- ((MainActivity) context).loginOut();
- }
- }
然后注册这个类,如下所示:
webView.addJavascriptInterface(new Mine(this.getActivity()), "mineInterface");
这样安卓端就写好了。接下来就是H5端调用了。
window.mineInterface.loginOut();
H5端直接这么调用就可以了。
如果js想传递json对象参数给安卓端怎么办,不要直接写json对象,要转换为json字符串,代码如下:
- window.mineInterface.loginOutTest(JSON.stringify({
- title: "iot",
- name: "iot"
- }));
安卓端接收如下:
- @JavascriptInterface
- public void loginOutTest(String params){
- Log.d(AppYunlanLink.TAG, "test: " + params);
- }
H5 我是用的vue 框架,方法写在了页面内,如下所示:
- created() {
- window.setUserInfo = this.setUserInfo; //android app 会调用此方法
- },
- methods: {
- setUserInfo(userInfo) {
- const _userInfo = JSON.parse(userInfo);
- this.userName = _userInfo.username;
- this.avatar = _userInfo.avatar;
- }
- },
注意方法一定要挂载到window对象上。安卓端怎么调用呢?
- //调用html5 页面中的方法,带JSONObject类型参数
- public void loadWebViewFuncWithJSON(String funcName, JSONObject value) {
- webView.post(new Runnable() {
- @Override
- public void run() {
- String _url = "javascript:" + funcName + "('" + value + "')";
- Log.d(AppYunlanLink.TAG, "value is: " + value);
- webView.loadUrl(_url);
- }
- });
- }
-
- fg4.loadWebViewFuncWithJSON("setUserInfo", info);
这是带有参数的调用,安卓端是JSONObject类型的,H5端接收的是json字符串。不带参数的调用更简单了,如下:
- //调用html5 页面中的方法
- public void loadWebViewFunc(String funcName) {
- String _url = "javascript:" + funcName + "()";
- webView.loadUrl(_url);
- }