android和js交互实例

本文详细介绍了如何在Android应用中使用WebView组件与JavaScript进行交互,包括添加接口、处理参数传递以及调用方法的完整实例。通过资产目录中的js文件和Activity中的代码实现按钮点击事件触发JavaScript操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)、两者交互的方法
WebView.addJavascriptInterface(Object object, String name)
(2)、实例内容包括:
1、JS端alert出”hello”
2、JS端alert出android传过来的参数 “content to js!”
3、JS端调用android方法1
4、JS端处理android传参并调用android方法2

完整的实例代码如下

一、layout布局代码

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

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <LinearLayout
        android:id="@+id/btnLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="#eee"
        android:visibility="gone" >

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button1" />
        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button2" />
        <Button
            android:id="@+id/button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button3" />
        <Button
            android:id="@+id/button4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Button4" />

    </LinearLayout>

</LinearLayout>

二、assets资源中的js代码(projectName/assets/js_java_interaction.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)
    }
</script>
Java-Javascript Interaction In Android
</html>

三、Activity中代码

public class AndroidInteractiveJsActivity extends Activity implements OnClickListener{

    private WebView myWebView;
    private LinearLayout btnLayout;
    private Button btn1, btn2, btn3, btn4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_interactive);
        btnLayout = (LinearLayout) findViewById(R.id.btnLayout);
        btn1 = (Button) findViewById(R.id.button1);
        btn2 = (Button) findViewById(R.id.button2);
        btn3 = (Button) findViewById(R.id.button3);
        btn4 = (Button) findViewById(R.id.button4);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);

        myWebView = (WebView) findViewById(R.id.webView);
        WebSettings settings = myWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        //addJavascriptInterface添加交互的类(类中方法需@JavascriptInterface)
        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);
                btnLayout.setVisibility(View.VISIBLE);
            }

        });
        myWebView.loadUrl("file:///android_asset/js_java_interaction.html");
    }
    //Java代码要实现这么一个类,它的作用是提供给Js调用
    public class JsInteration {

        @JavascriptInterface
        public void toastMessage(String message) {
            Toast.makeText(AndroidInteractiveJsActivity.this, message, Toast.LENGTH_LONG).show();
        }

        @JavascriptInterface
        public void onSumResult(int result) {
            Toast.makeText(AndroidInteractiveJsActivity.this, "result = "+result, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            myWebView.loadUrl("javascript:sayHello()");
            break;
        case R.id.button2:
            myWebView.loadUrl("javascript:alertMessage(\"" + "content to js!" + "\")");     
            break;
        case R.id.button3:
            myWebView.loadUrl("javascript:toastMessage(\"" + "toast content" + "\")");
            break;
        case R.id.button4:
            myWebView.loadUrl("javascript:sumToJava(10,20)");
            break;
        default:
            break;
        }
    }
}

可能存在的问题及答案
1、Alert无法弹出
你应该是没有设置WebChromeClient,按照以下代码设置
myWebView.setWebChromeClient(new WebChromeClient() {});
2、Uncaught ReferenceError: functionName is not defined 是因为网页的js代码没有加载完成
3、All WebView methods must be called on the same thread
因为在js调用后的Java回调线程并不是主线程,解决上述的异常,将webview操作放在主线程中即可。
webView.post(new Runnable() {
@Override
public void run() {
webView.loadUrl(YOUR_URL);
}
});

来源:网络

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值