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

WebView相關(guān)設(shè)置
WebSettings mWebSettings = getSettings();mWebSettings.setDefaultTextEncodingName("UTF-8");//設(shè)置默認的顯示編碼mWebSettings.setJavaScriptEnabled(true);//調(diào)用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調(diào)用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調(diào)用JS代碼-成功!!!'+JSON.stringify(result); } </script></head><body><button id="button_call">Js調(diào)用Android代碼</button><div id="div_bg"></div></body></html>感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答