android 实现webview jsBridge 通信

95 阅读1分钟

android 实现webview jsBridge 通信

一.java类 实现webview 挂载app

1.新建一个页面,对应一个java类和一个xml文件:

xml:

<RelativeLayout 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"
    tools:context="com.linsheng.FATJS.activitys.MainActivity">
    
    <WebView
        android:id="@+id/wv_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

java类:

public class WebviewPage extends AppCompatActivity {
    private static final String TAG = "webviewPage";
    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_page);
        webViewInit();
        addJsBridge();

    }
    protected void webViewInit(){
        //获得控件
        webView = (WebView)  findViewById(R.id.wv_webview);
        webView.loadUrl("http://192.168.31.44:4200/");
        //系统默认会通过手机浏览器打开网页,为了能够直接通过WebView显示网页,则必须设置
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url){
                view.loadUrl(url);
                return true;
            }
        });
        //声明WebSettings子类
        WebSettings webSettings =webView.getSettings();

        //如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webView.clearCache(true); //清除页面缓存
        //设置自适应屏幕,两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
    }

    public void addJsBridge(){
        Log.e(TAG,"hello1");
        webView.addJavascriptInterface(new MyJavascriptInterface(this),"AndroidBridge");
    }

}

2.新增一个java类,用以实现向webview 提供的方法 示例实现了webview 返回两个数,用以计算两数之和,并且调用android 原生实现弹窗

public class MyJavascriptInterface {
    private static final String TestApp="TestApp";
    public Context appContext;
    public MyJavascriptInterface(Context viewContext){
        appContext=viewContext;
    }
    @JavascriptInterface
    public void showToast(int num1,int num2) {
        int sum = num1 + num2;
        String res =String.valueOf(num1)+"+"+String.valueOf(num2)+"=" + sum;
        AlertDialog.Builder builder = new AlertDialog.Builder(appContext);
        builder.setMessage(res)
                .setTitle("计算结果")
                .setPositiveButton("确定", null)
                .show();
    }
}

3.在AndroidManifest.xml配置文件添加权限允许访问外部资源,并且application 添加android:usesCleartextTraffic="true"以允许http 通信

  <!--添加webview 访问外部资源权限 -->
 <uses-permission android:name="android.permission.INTERNET" />

 <application
        android:name="com.linsheng.FATJS.reporter.SampleApplication"
        android:allowBackup="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:usesCleartextTraffic="true"
        android:supportsRtl="true"
        android:requestLegacyExternalStorage="true"
        android:theme="@style/AppTheme">
        <!--android:usesCleartextTraffic="true" 是否允许http通信-->

二.webview 实现

<template>
  <div class="about">
    <div style="color: red;">This is an about page</div>
    <button @click="AppMethods">调用app方法</button>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted } from 'vue'

  const AppMethods = ()=>{
    let that_window:any = window
    that_window.AndroidBridge.showToast(1,2);
    alert("hello")
  }
  onMounted(() => {
    console.log(`the component is now mounted.`)
  })
</script>
<style>
@media (min-width: 1024px) {
  .about {
    min-height: 100vh;
    display: flex;
    align-items: center;
  }
}
</style>

效果图

image-20230823094640984image-20230823094715119