JavaScript與Android Native的交互

JavaScript與Android Native的交互

添加WebView到你的Android Application

首先在你的activity layout裏面添加一個標籤:

<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

在activity裏面加載一個WebView:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
//myWebView.loadUrl("file:///android_asset/index.html");

因爲WebView需要訪問網絡,所以需要在Manifest文件中添加訪問網絡的權限:

<uses-permission android:name="android.permission.INTERNET" />

在WebView中使用JavaScript

默認情況下在WebVIew中是不能使用JavaScript的,如果想使用需要在WebView中添加一個設置:

WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

JavaScript調用Android Native代碼

當WebView中的JavaScript代碼需要調用Android Native代碼,例如在WebView中點擊一個按鈕時需要在Android Native中顯示一個Toast,而不是JavaScript中的alert。首先你需要定義一個類,如下:

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public String modifyString(String inputString) {
        return inputString + " from Java side";
    }
}

在API 17之後需要調用的方法前加上一個annotation @JavascriptInterface,否則在JavaScript中是調不到這個方法的。這是一個安全策略,否則Js可以調用Java對象方法,通過反射機制,Js可以直接獲取Runtime,從而執行任意命令。
使用addJavascriptInterface()將上述代碼加到WebView中:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");//"Android"實在JavaScript中調用的名字

下面是WebView中調用該代碼的例子:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
        var stringFromJava =Android.modifyString("string from javascript");//有返回值
    }
</script>

Android Native代碼調用JavaScript代碼

目前向JavaScript傳遞的參數只支持String類型,且不支持返回值。如果有返回的需求是需要在JavaScript中自己去主動調動用Android Native中的方法並將需要傳入的值當做參數傳入。

webView.loadUrl("javascript:document.getElementById(‘id’).innerHTML = ‘changed’ ");//操作DOM元素

String mes="hello world";
webView.loadUrl("javascript:window.Android.showToast("+ mes +")");
webView.loadUrl("javascript:showAndroidToast("+ mes +")");

調試WebView

在Android4.4 KITKAT之後支持調試WebView:

 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
     WebView.setWebContentsDebuggingEnabled(true);
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章