Android與JS之間跨平台非同步呼叫執行個體詳解_Android

來源:互聯網
上載者:User

Android與JS之間跨平台非同步呼叫

 為什麼突然要搞這個問題呢?

   在開發瀏覽器的時候遇到這個狗血的問題,花了將近1天的時間才想到這個解決方案,Android與JavaScirpt互調。

  因為介面是抓取的別人的,所以出現了JS跨域問題,Android閃亮登場搞定了。

 GIF動畫示範

  

  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>

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.