標籤:java js代碼 http ebs span github 方法 override 總結
一、JS與Android
放在了assets檔案夾下了(注意若使用的是AS這個IDE,assets檔案夾應放在src/main目錄下)
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>葛夫鋒</title> <script> function callAndroid(){ test.hello("js調用了android中的hello方法"); } </script> </head> <body> <button type="button" id="button1" onclick="callAndroid()">js調用android中的代碼</button> </body></html>
代碼非常簡單,頁面中就一個按鈕,點擊這個按鈕調用callAndroid函數,這裡需注意callAndroid函數中的語句是android中對外的的一個函數,在android中的代碼:
{ ... webSettings.setJavaScriptEnabled(true); webView.addJavascriptInterface(this, "test");//對應js中的test.xxx webView.loadUrl("file:///android_asset/js_web.html");}@JavascriptInterfacepublic void hello(String msg){//對應js中xxx.hello("") Log.e("webview","hello"); Toast.makeText(this,msg,Toast.LENGTH_LONG).show();}
這裡需注意的是hello函數加上註解@javascriptInterface,這樣點擊html中的按鈕就會調用android中的hello方法了。
二、Android調用JS代碼
js代碼如下:
<script> function callJS(){ alert("android調用了js中的callJS方法"); }</script>
android代碼如下:
public void click(View view){ webView.post(new Runnable() { @Override public void run() { webView.loadUrl("javascript:callJS()"); } });}
當android中的按鈕被點擊時會觸發click方法,然後執行webview.loadUrl("javascript:callJS()"),然後js中正好有callJS這個方法,然後alert()就會被執行。
這個總結很好:
https://github.com/shaojiankui/iOS-WebView-JavaScript
JS與IOS、Android的互動