本文主要介绍利用 JavascriptInterface 实现 Android 和 H5 界面的交互。
因为是 Android 的技术分享,js 具体代码就不贴了,只要知道前端给的
这个方法就够了。
- Consume.getwebId("invest")
下面开始介绍 Android 代码:
- private Activity activity;
- public H5Operator(Activity activity) {
- this.activity = activity;
- }
- @JavascriptInterface
- public void getWebId(final String message){
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if("invest".equals(message)){
- //在这里执行你想要的操作;
- }
- }
- });
- }
代码说明:getWebId 必须要和前端的一致,
匹配收到的 message,然后执行 android 自己的操作,比如跳转之类的。
- //核心方法代码
- @SuppressLint({
- "NewApi",
- "SetJavaScriptEnabled"
- }) private void initializeWebView() {
- webView.addJavascriptInterface(new H5Operator(WebViewActivity.this), "Consume");
- try {
- String userId = (String) SPutils.get(this, "userId", "0");
- String url = "访问的界面";
- WebSettings webSettings = webView.getSettings();
- webSettings.setJavaScriptEnabled(true);
- webSettings.setAllowFileAccess(true);
- webSettings.setAllowFileAccessFromFileURLs(true);
- webSettings.setBuiltInZoomControls(false);
- webSettings.setSupportZoom(false);
- webSettings.setDisplayZoomControls(false);
- this.webView.loadUrl(url);
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- //在onCreate方法中调用
- this.initializeWebView();
代码说明:
NewApi 作用是屏蔽 android lint 错误,
开启 Javascript 支持。
- SetJavaScriptEnabled
这句代码中需要注意的是 "Consume" 必须和前端给的方法一致。
- webView.addJavascriptInterface(new H5Operator(H5Operator.this), "Consume");
以上,就是 Android 和 H5 交互的方法,很简单,其他延伸的知识就不在这赘述了。详细的分享 这篇讲挺多的 ,大家可以参考下。
来源: http://www.jianshu.com/p/01cb75616619