135、JS和Android交互范例

很简单的直接上代码

<uses-permission android:name="android.permission.INTERNET" />
assets/web.html
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=gb2312">
    <script type="text/javascript">

function javacalljs(){
     document.getElementById("content").innerHTML =
         "<br\>JAVA调用了JS的函数";
}

function javacalljswith(arg){
     document.getElementById("content").innerHTML =
         ("<br\>"+arg);
}
    </script>
</head>
<body>
        HTML 内容显示 <br/>
<h1>
    <div id="content">内容显示</div>
</h1>
<br/>
<input type="button" value="点击调用java代码" onclick="window.android.startFunction()"/>
<br/>
<input type="button" value="点击调用java代码并传递参数"
       onclick="window.android.startFunction('http://blog.csdn.net/Leejizhou')"/>
</body>
</html>
package com.leejz.jsdemo;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private WebView contentWebView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contentWebView = (WebView) findViewById(R.id.webview);
        // 启用javascript
        contentWebView.getSettings().setJavaScriptEnabled(true);
        // 从assets目录下面的加载html
        contentWebView.loadUrl("file:///android_asset/web.html");
        contentWebView.addJavascriptInterface(MainActivity.this, "android");

        //无参调用Js点击
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 无参数调用  WebView中显示  JAVA调用了JS的函数
                contentWebView.loadUrl("javascript:javacalljs()");
            }
        });
        //有参调用Js点击
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 传递参数调用    WebView中显示  www.baidu.com
                contentWebView.loadUrl("javascript:javacalljswith("
                        + "'www.baidu.com'" + ")");
            }
        });
    }

    //由于安全原因 需要加 @JavascriptInterface
    @JavascriptInterface
    public void startFunction() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "吐司", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @JavascriptInterface
    public void startFunction(final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(MainActivity.this).setMessage(text).show();
            }
        });
    }
}

 

posted on 2017-11-14 14:27  大米稀饭  阅读(381)  评论(0编辑  收藏  举报