欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

原生和js交互 简单代码

程序员文章站 2024-03-17 11:20:16
...

清单文件

<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:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#00ff00">

            <WebView
                android:id="@+id/web_id"
                android:layout_width="400dp"
                android:layout_height="400dp"
                />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

MainActivity

package com.example.dell.webviewjs;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button tojs;
    WebView webView;
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.web_id);

        tojs = findViewById(R.id.calljs_but_id);

        WebSettings webSettings = webView.getSettings();
        // 设置与Js交互的权限
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        //设置对象映射
        webView.addJavascriptInterface(new JsToAndroid() , "test");

        // 先载入JS代码
        // 格式规定为:file:///android_asset/文件名.html
        webView.loadUrl("file:///android_asset/text.html");

        alteView(webView);



        tojs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String result = "你好";
                //        webView.loadUrl("javascript:returnResult(" + result + ")");

                webView.loadUrl("javascript:returnResult()");

            }
        });

    }


    public class JsToAndroid{
        @JavascriptInterface
        public void hello(final String str ){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this , str , Toast.LENGTH_LONG).show();
                }
            });
        }
    }


    public void alteView(WebView webView){

        //    webView.setWebChromeClient(new WebChromeClient());
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                Log.e("tag" ,"执行次数");
                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                //     b.create().show();

                return super.onJsAlert(view, url, message, result);
            }
        });
    }
}

在src/main/assets 创建assets 导入一个.html

text.html


<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <title>Carson</title>  
      <script>
         function callAndroid(){
            test.hello("js调用了android中的hello方法");
         }

         function returnResult(){
            alert("result is");
            }
      </script>
   </head>


   <body>
      <button type="button" id="button1" onclick="callAndroid()"> 调用安卓代码 </button>
   </body>


</html>