Java与Js互调

现在越来越多的应用涉及到java与H5的混合开发,所以java与js的互调会经常使用,下面简单介绍下基本使用方式

一、java调用js

java调用js主要通过WebView中loadUrl()方法进行调用
1、通过如下设置启用javaScript
// 启用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
2、加载js网址
简单写了个js静态网页放到assets中
提供了两个方法javaCallJs()和javaCallJsWithArgs(arg)供java代码调用
<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 javaCallJsWithArgs(arg){
     document.getElementById("content").innerHTML +=     
         ("<br\>"+arg);  
}  

</script>  
</head>  
<body>  
this is my html <br/><br>
<button onClick="window.callJava.Function4Js()">调用java代码</button><br/><br>
<button onClick="window.callJava.Function4Js('call java')" >含参调用java代码</button></body></br><br>
<div id="content">content:</div>
</body>  
</html> 

assets中添加html文件
这里写图片描述

// 从assets目录下面的加载html文件
 mWebView.loadUrl("file:///android_asset/js_test.html");
 加载js中方法
// 无参调用
 mWebView.loadUrl("javascript:javaCallJs()");
 // 传参调用
String str="transfer parameter";
String call="javascript:javaCallJsWithArgs(\"" + str + "\")";
            mWebView.loadUrl(call);
注意:**对于字符串作为参数值需要进行转义双引号**

二、js调用java代码

1、java中提供供js调用的接口,并指定接口名

mWebView.addJavascriptInterface(this, "callJava");

2、提供方法用于js调用

   /**
     * @JavascriptInterface 添加js调用注解
     */
    @JavascriptInterface
    public void Function4Js() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                msgView.setText(msgView.getText() + "\njs调用了java函数");

            }
        });
    }
    @JavascriptInterface
    public void Function4Js(final String str) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                msgView.setText(msgView.getText() + "\njs调用了java函数传递参数:" + str);


            }
        });
    }

3、js中点击事件设置调用java指定方法

<button onClick="window.callJava.Function4Js()">调用java代码</button><br/><br>
<button onClick="window.callJava.Function4Js('call java')" >含参调用java代码</button></body></br><br>

ok看下总体效果吧
这里写图片描述

全部代码

package net.edaibu.testapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

/**
 * @author geqipeng
 * @date 2017/11/14
 */

public class JsCallJavaActivity extends Activity {

    private WebView mWebView = null;
    private TextView msgView = null;

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_js_call_java);
        initView();

    }

    private void initView() {
        mWebView = findViewById(R.id.webview);
        msgView = findViewById(R.id.msg);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(btnClickListener);
        initWebViewSetting();
    }

    /**
     * webView设置
     */
    private void initWebViewSetting() {
        // 启用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        // 从assets目录下面的加载html
        mWebView.loadUrl("file:///android_asset/js_test.html");
        mWebView.addJavascriptInterface(this, "callJava");
    }

    /**
     * @JavascriptInterface 添加js调用注解
     */
    @JavascriptInterface
    public void Function4Js() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                msgView.setText(msgView.getText() + "\njs调用了java函数");

            }
        });
    }
    @JavascriptInterface
    public void Function4Js(final String str) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                msgView.setText(msgView.getText() + "\njs调用了java函数传递参数:" + str);


            }
        });
    }

    private View.OnClickListener btnClickListener = new Button.OnClickListener() {
        public void onClick(View v) {

            // 无参调用
            mWebView.loadUrl("javascript:javaCallJs()");
            // 传参调用
            mWebView.loadUrl("javascript:javaCallJsWithArgs(" + "'transfer parameter '" + ")");
        }
    };
}

布局

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

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

    <TextView
        android:id="@+id/msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:textColor="#ff0000"
        android:textSize="14sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="点击调用js方法" />

</LinearLayout>

js代码前面给了,就不贴了

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是的,可以使用WebViewJavaScript与Android中Java方法互调。 想要实现这个功能,需要使用到Android中的WebView的addJavascriptInterface方法。这个方法可以将Java对象暴露给JavaScript代码,JavaScript代码就可以调用这个对象的方法,实现JavaJavaScript的互通。 具体步骤如下: 1. 在Java代码中创建一个类,这个类中包含需要暴露给JavaScript的方法。 2. 使用WebView的addJavascriptInterface方法将这个Java类对象暴露给JavaScript。 3. 在JavaScript代码中,使用window对象来访问这个Java对象,即可调用其中的方法。 具体的实现可以参考下面的代码示例: Java代码: ```java 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(); } } ``` 在Activity中使用addJavascriptInterface方法将Java对象暴露给JavaScript: ```java WebView webView = (WebView) findViewById(R.id.webview); webView.addJavascriptInterface(new WebAppInterface(this), "Android"); ``` JavaScript代码中通过window对象访问Java对象: ```javascript function showToast() { Android.showToast("Hello World!"); } ``` 注意,addJavascriptInterface方法需要在主线程中调用,否则可能会出现安全问题。另外,在使用JavaScript调用Java方法时,需要添加@JavascriptInterface注解,以确保安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值