JS与安卓的通信
来源:互联网 发布:网络分线器怎么用 编辑:程序博客网 时间:2024/05/17 04:43
JS与安卓的通信包括了安卓调用JS,JS调用安卓以及比较常用的使用callback方式调用.
要调用JS,首先要开启JS,调用websetting的setJavaScriptEnable(true);接着需要设置webview的加载打开方式,setWebViewClient(),setChromClient(),需要重写里面的方法.
首先,安卓调用JS,需要调用方法
mWebView.loadUrl("javascript:js中的方法名(方法参数)");
JS调用安卓,需要借助桥梁类,所以在安卓代码中先创建一个桥梁类,里面是JS要调用的方法.接着,需要调用的webview的addJavaScriptInterface(桥梁类对象,桥梁对象的映射字符串).
callback回调的步骤是:
1.在JS代码中创建参数变量,里面包含了callback元素,然后通过调用安卓方法,将参数传递过去,这里的callback作为了JS代码提供安卓调用的方法的占位符,避免了后期可能发生的JS代码方法名的改变;
2.在安卓的桥梁类对应的方法中解析出传递过来的calback,然后就可自由的添加想要传递给JS的数据,回调JS中callback代表的方法
代码示例如下:
安卓端代码:
public class MainActivity extends AppCompatActivity { private WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mWebView = (WebView) findViewById(R.id.wv);WebSettings settings = mWebView.getSettings();settings.setJavaScriptEnabled(true);mWebView.setWebViewClient(new WebViewClient(){ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {super.onPageStarted(view, url, favicon); } @Override public void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);try { //安卓调用JS代码 JSONObject jsonObject = new JSONObject() ; jsonObject.put("name","android"); jsonObject.put("message","hello,brother,have a frind?"); mWebView.loadUrl("javascript:showMessage("+ jsonObject.toString() +")");} catch (JSONException e) { e.printStackTrace();} }});mWebView.setWebChromeClient(new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) {super.onProgressChanged(view, newProgress); } @Override public void onReceivedTitle(WebView view, String title) {super.onReceivedTitle(view, title); }});Bridge bridge = new Bridge(this,mWebView);mWebView.addJavascriptInterface(bridge,"jsInterface");//注意:这里的地址需要保证模拟器与电脑主机是在同一网段mWebView.loadUrl("http://192.168.23.1:8080/jsandandroid/jsnandroid.html"); }}
布局文件activity_main.xml
<pre name="code" class="java"><?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:id="@+id/wv" android:layout_width="match_parent" android:layout_height="match_parent"> </WebView></RelativeLayout>桥梁类Bridget
<pre name="code" class="java">public class Bridge { Context mContext; WebView mWebView; Handler mHandler = new Handler(); public Bridge(Context context, WebView webView) {mContext = context;mWebView = webView; } @JavascriptInterface public void showToast(String json) {Toast.makeText(mContext, json, Toast.LENGTH_LONG).show(); } @JavascriptInterface public void getCallback(String json) {//获取js传递过来的数据,并解析出方法名try { JSONObject jsonObject = new JSONObject(json); final String callback = jsonObject.optString("callback"); //根据获得的方法名,安卓进行回调,回调前封装数据过去 //封装数据 final JSONObject data = new JSONObject(); data.put("name", "zhangsan"); data.put("age", "38"); data.put("sex", "gender"); data.put("des", "i will,i can");// Toast.makeText(mContext,json,Toast.LENGTH_LONG).show(); mHandler.post(new Runnable() {@Overridepublic void run() { //回调,需要保证在主线程中 mWebView.loadUrl("javascript:" + callback + "(" + data.toString() + ")");} });} catch (JSONException e) { e.printStackTrace();} }}H5的代码
<pre name="code" class="html"><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <!--屏幕适配,必须加上viewport--> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <link rel="stylesheet" href="css/jquery.mobile-1.4.5.min.css"> <script src="js/jquery.min.js"></script> <script src="js/jquery.mobile-1.4.5.min.js"></script> <title>安卓与JS通信</title> <style> *{ padding: 0; margin: 0; } #wrrap{ padding: 10px; } button{ width: 100%; height: 38px; line-height: 38px; border-style: none; border-radius: 8px; background-color: #005599; text-align: center; color: white; } button:active{ background-color: #666666; } </style></head><body id="wrrap"><button id="btn1">js调用安卓方法</button><button id="btn2">js调用安卓方法(callback)</button><!--处理点击事件--><script> $("#btn1").on("click",function(){ alert("sfsf"); console.log("点击了js调用安卓方法"); var json = {"name":"js","message":"fuck,leave me alone!"}; window.jsInterface.showToast(JSON.stringify(json)); }); $("#btn2").on("click",function(){ console.log("点击了js调用安卓方法(callback)"); //将安卓需要调用的方法名以callback方式传递 var json = {"name":"js","callback":"methodName"}; window.jsInterface.getCallback(JSON.stringify(json)); });// js中的方法 function showMessage(json){ alert(JSON.stringify(json)); }; function methodName(json){ console.log("callback执行了"); alert(JSON.stringify(json)); };</script></body></html>
1 0
- JS与安卓的通信
- 安卓与JS通信相互调用
- 安卓与pc 的socket通信
- 安卓与pc 的socket通信
- Unity与安卓通信
- 安卓开发中服务器与客户端的通信
- 安卓与51单片机的蓝牙通信(安卓端)
- 安卓开发之Fragment的使用与通信
- 安卓PC实现通信与UDP的Java实现
- 安卓手机与蓝牙串口模块的通信
- 安卓客户端与服务器端的简单通信
- JCFXBL与WebView整合打造安卓应用服务平台(js -java/andriod通信window.JavaObj)
- 安卓的通信机制
- 安卓与js交互
- 安卓与js互调
- 安卓与js调用
- 安卓与JS交互
- webview与js的通信
- VxWorks上从romInit跳转到romStart时的地址计算
- 安装easy_install和pip
- *浙大甲级PAT 1109
- [pySpark][note]Linear Regression
- Oracle Data Provider for .NET, Managed Driver
- JS与安卓的通信
- NOIP2015 提高组 day1 信息传递
- Java中不编写返回引用对象的访问器方法
- yii2 高级版 多版本支持
- DOM Element对象的offsetXXX方法
- Lucas定理模版、
- Android联系人数据库读取
- 【mysql】事务死锁问题
- Android之利用android:indeterminateDrawable来实现ProgressBar三种方式