Android与JS之间跨平台异步调用

时间:2021-12-28 07:56:17

 为什么突然要搞这个问题呢?

   在开发浏览器的时候遇到这个狗血的问题,花了将近1天的时间才想到这个解决方案,Android与JavaScirpt互调。

  因为接口是抓取的别人的,所以出现了JS跨域问题,Android闪亮登场搞定了。

GIF动画演示

  Android与JS之间跨平台异步调用

WebView相关设置

WebSettings mWebSettings = getSettings();
mWebSettings.setDefaultTextEncodingName("UTF-8");//设置默认的显示编码

mWebSettings.setJavaScriptEnabled(true);//调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface

直接放大招->贴代码

 Android

  

         addJavascriptInterface(new Object() {
@JavascriptInterface
public void toastMessage(final String url, final int type, final int dir) {
L.e("url = " + url + " type = " + type + " dir = " + dir);
APIWrapper.getInstance()
.getLenovoWord(url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new RxSubscriber<ResponseBody>() {
@Override
public void _onNext(ResponseBody responseBody) {
try {
String data = responseBody.string();
L.e("data = " + data);
loadUrl("javascript:ResCompleted(" + data + "," + type + "," + dir + ")");
} catch (IOException e) {
e.printStackTrace();
}
} @Override
public void _onError(String msg) {
loadUrl("javascript:ResCompleted(" + msg + ")");
}
});
}
}, "Android");

 Html

 <html>
<meta name="viewport"
content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;">
<head> <title>Js调用Android代码</title>
<style>
#button-call{
width: 100%;
padding: 20px;
font-size: 20px;
}
#div_bg{
background: #cccccc;
margin-top: 50px;
}
</style>
<script type="text/javascript">
window.onload=function() {
document.getElementById('button_call').onclick=function(){
window.Android.toastMessage("http://api.sina.cn/sinago/list.json?channel=news_toutiao",1, 0);
}
} function ResCompleted(result,type,dir) {
document.getElementById('div_bg').innerHTML='Android调用JS代码-成功!!!'+JSON.stringify(result);
} </script>
</head> <body>
<button id="button_call">Js调用Android代码</button>
<div id="div_bg"></div>
</body> </html>