天天看點

Android的webview加載本地html、assert内html和網絡URL&&& JS與移動端webview的互相互動

Android的webview加載本地html、assert内html和網絡URL:

//打開本包内asset目錄下的test.html檔案

wView.loadUrl(" file:///android_asset/test.html ");  

//打開本地sd卡内的kris.html檔案

wView.loadUrl("file:///mnt/sdcard/test.html");

WebView.loadUrl("file://"+"/mnt/sdcard/"+"index.html");

wView.loadUrl("content://com.android.htmlfileprovider/sdcard/kris.html");

//打開指定URL的html檔案

wView.loadUrl("http://www.krislq.com/");

JS與移動端webview的互相互動:

随着h5在移動端的普及,移動端對webview的使用越來越平凡,有的界面也不僅僅局限于網頁的顯示,很多時候就要涉及到webview與javascript代碼之間的互動,這對于移動端工程師和web端工程師都是一個挑戰,下面來總結下它們之間的互動和注意事項。

1.先說js中調用android代碼:下面是我寫的一段簡單的js代碼:放在了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");
}
@JavascriptInterface
public void hello(String msg){//對應js中xxx.hello("")
    Log.e("webview","hello");
    Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
}
           

這裡需注意的是hello函數加上注解@javascriptInterface,這樣點選html中的按鈕就會調用android中的hello方法了。

2.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()就會被執行,這裡需要注意的是在android的代碼中我沒有直接寫

webView.loadUrl("javascript:callJS()");
           

而是加了一個post(new Runble),若不加的話js代碼是不被調用的。

好了,是不是so easy,android與js的簡單互動就是這樣,歡迎補充

繼續閱讀