Android與JS之間跨平台異步調用,androidjs異步
為什麼突然要搞這個問題呢?
在開發浏覽器的時候遇到這個狗血的問題,花了將近1天的時間才想到這個解決方案,Android與JavaScirpt互調。
因為接口是抓取的別人的,所以出現了JS跨域問題,Android閃亮登場搞定了。
GIF動畫演示

WebView相關設置
WebSettings mWebSettings = getSettings();
mWebSettings.setDefaultTextEncodingName("UTF-8");//設置默認的顯示編碼
mWebSettings.setJavaScriptEnabled(true);//調用JS方法.安卓版本大於17,加上注解 @JavascriptInterface
直接放大招->貼代碼
Android

![]()
1 addJavascriptInterface(new Object() {
2 @JavascriptInterface
3 public void toastMessage(final String url, final int type, final int dir) {
4 L.e("url = " + url + " type = " + type + " dir = " + dir);
5 APIWrapper.getInstance()
6 .getLenovoWord(url)
7 .subscribeOn(Schedulers.io())
8 .observeOn(AndroidSchedulers.mainThread())
9 .subscribe(new RxSubscriber<ResponseBody>() {
10 @Override
11 public void _onNext(ResponseBody responseBody) {
12 try {
13 String data = responseBody.string();
14 L.e("data = " + data);
15 loadUrl("javascript:ResCompleted(" + data + "," + type + "," + dir + ")");
16 } catch (IOException e) {
17 e.printStackTrace();
18 }
19 }
20
21 @Override
22 public void _onError(String msg) {
23 loadUrl("javascript:ResCompleted(" + msg + ")");
24 }
25 });
26 }
27 }, "Android");
View Code
Html

![]()
1 <html>
2 <meta name="viewport"
3 content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;">
4 <head>
5
6 <title>Js調用Android代碼</title>
7 <style>
8 #button-call{
9 width: 100%;
10 padding: 20px;
11 font-size: 20px;
12 }
13 #div_bg{
14 background: #cccccc;
15 margin-top: 50px;
16 }
17 </style>
18 <script type="text/javascript">
19 window.onload=function() {
20 document.getElementById('button_call').onclick=function(){
21 window.Android.toastMessage("http://api.sina.cn/sinago/list.json?channel=news_toutiao",1, 0);
22 }
23 }
24
25 function ResCompleted(result,type,dir) {
26 document.getElementById('div_bg').innerHTML='Android調用JS代碼-成功!!!'+JSON.stringify(result);
27 }
28
29 </script>
30 </head>
31
32 <body>
33 <button id="button_call">Js調用Android代碼</button>
34 <div id="div_bg"></div>
35 </body>
36
37 </html>
View Code