Adriod与HTML+JS的交互

本篇主要实现的功能点:

  • Android 调用HTML中的javascript脚本
  • HTML中的javascript脚本调用Android本地代码
  • Android 调用HTML中的javascript脚本并传递参数
  • HTML中的javascript脚本调用Android本地代码并传递参数

实现Android调用JS脚本是非常简单的,直接Webview调用loadUrl方法,里面是JS的方法名,并可以传入参数,javascript:xxx()方法名需要和JS方法名相同

contentWebView.loadUrl("javascript:javacalljs()");

HTML代码 

实现JS调用Android方法,需要在Java代码中添加下面这句,webview绑定javascriptInterface,js脚本通过这个接口来调用java代码, 第一个参数是自定义类对象,映射成JS对象,这里我直接传this,第二个参数是别名,JS脚本通过这个别名来调用java的方法,这个别名跟HTML代码中也是对应的。

 contentWebView.addJavascriptInterface(MainActivity.this,"android");

HTML代码

 

下面是具体的实现步骤:

先建立一个HTML文件,很简单,里面主要有两个按钮,两个JS方法

<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>

需要把这个HTML文件放到assets文件夹中 注意文件夹位置

添加权限

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

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Android"
      />
    <Button
        android:id="@+id/button"
        android:layout_margin="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="调用JS"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        />
    <Button
        android:id="@+id/button2"
        android:layout_margin="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="调用有参JS"
        android:background="@color/colorAccent"
        android:textColor="#ffffff"
        />


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="WebView"
        android:layout_marginTop="8dp"
        />

    <WebView

        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />

</LinearLayout>

Activity 的java类

public class MainActivity extends AppCompatActivity {
    private WebView contentWebView;

 @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");


        //Button按钮 无参调用HTML js方法
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 无参数调用 JS的方法  
                contentWebView.loadUrl("javascript:javacalljs()");

            }
        });
        //Button按钮 有参调用HTML js方法
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 传递参数调用JS的方法
                contentWebView.loadUrl("javascript:javacalljswith(" + "'http://blog.csdn.net/Leejizhou'" + ")");
            }
        });


    }

    //由于安全原因 targetSdkVersion>=17需要加 @JavascriptInterface 
    //JS调用Android JAVA方法名和HTML中的按钮 onclick后的别名后面的名字对应
    @JavascriptInterface
    public void startFunction(){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this,"show",3000).show();

            }
        });
    }

    @JavascriptInterface
    public void startFunction(final String text){
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
               new AlertDialog.Builder(MainActivity.this).setMessage(text).show();

            }
        });


    }
}

Ok 这样一个简单的Android与HTML+JS的交互就完成了(此文参考)

 IOS可参考http://blog.csdn.net/wangjia55/article/details/50905315与https://www.jianshu.com/p/f896d73c670a

原文地址:https://www.cnblogs.com/yiyi17/p/8512530.html