1. 程式人生 > >Android webview載入Html頁面,傳參到Html並獲取返回值

Android webview載入Html頁面,傳參到Html並獲取返回值

1.Android端程式碼

public class MainActivity extends Activity {

private static final String LOGTAG = "MainActivity";
@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final WebView myWebView = (WebView) findViewById(R.id.myWebView);

    WebSettings settings = myWebView.getSettings();
    settings.setJavaScriptEnabled(true);//設定JS可用
    myWebView.addJavascriptInterface(new JsInteration(), "control");//傳遞物件進行互動
    myWebView.setWebChromeClient(new WebChromeClient() {});
    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//當頁面載入完成
            super.onPageFinished(view, url);            


           if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){//當Android SDK>=4.4時
               callEvaluateJavascript(myWebView);
           }else {
            callMethod(myWebView);
           }
      }

    });
    myWebView.loadUrl("file:///android_asset/js_java_interaction.html");
}

private void callMethod(WebView webView) {
    String call = "javascript:sayHello()";

    call = "javascript:alertMessage(\"content\")";

   // call = "javascript:toastMessage(\"Hello World\")";

    //call = "javascript:sumToJava(1,2)";

    //call = "javascript:mult1(3,3)";

    webView.loadUrl(call);

}

public class JsInteration {

    @JavascriptInterface
    public void toastMessage(String message) {

        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
    }

    @JavascriptInterface
    public void onSumResult(int result) {

        System.out.println(LOGTAG+"_onSumResult result=" + result);
    }

    @JavascriptInterface
    public void onMultResult(int result) {

        System.out.println(LOGTAG+"_onMultResult result=" + result);
    }
}

private void callEvaluateJavascript(WebView webView) {

      webView.evaluateJavascript("mult2(3,3)", new ValueCallback<String>() {

      @Override
      public void onReceiveValue(String value) {         

          System.out.println(LOGTAG+"_onReceiveValue value=" + value);
          Toast.makeText(MainActivity.this, "onReceiveValue value=" + value, Toast.LENGTH_LONG).show();
      }});
    }

}

2.Html頁面

<html> <script type="text/javascript">   
       function sayHello() {   alert("Hello")    }
       function alertMessage(message) {   alert(message)    }
       function toastMessage(message) 
       {  window.control.toastMessage(message)    }
       function sumToJava
(number1, number2){
window.control.onSumResult(number1 + number2) } function mult1(x,y) { window.control.onMultResult(x*y) } function mult2(x,y) { return x*y; } function sub(x,y) { return x-y; } <body> <center
>
<p>Android與Javascript之間的互動.</p> </center> </body> </html>