WebAppInterface.java(必须存在)
package com.example.chapter05;import android.content.Context;
import android.webkit.JavascriptInterface;
import android.widget.Toast;public class WebAppInterface {Context mContext;WebAppInterface(Context c) {mContext = c;}@JavascriptInterfacepublic void receiveDataFromAndroid(String data) {Toast.makeText(mContext, "收到数据: " + data, Toast.LENGTH_SHORT).show();}@JavascriptInterfacepublic void receiveUserData(String name, int age, String jsonExtra) {}
}
package com.example.chapter05;import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowInsetsController;
import android.webkit.WebView;
import android.webkit.WebViewClient;import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private WebView webView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);View decorView = getWindow().getDecorView();getWindow().setStatusBarColor(Color.TRANSPARENT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {getWindow().getInsetsController().setSystemBarsAppearance(WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);} else {decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE |View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR );}webView = findViewById(R.id.webview);webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setDomStorageEnabled(true); webView.addJavascriptInterface(new WebAppInterface(this), "Android");webView.setWebViewClient(new WebViewClient() {@Overridepublic void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {super.onPageStarted(view, url, favicon);Log.d("WebView", "页面开始加载: " + url);}@Overridepublic void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);Log.d("WebView", "页面加载完成: " + url);updateUIForUrl(url);String username = "your_username"; String password = "your_password"; String safeUsername = username.replace("'", "\\'");String safePassword = password.replace("'", "\\'");String jsCode = String.format("javascript:(function() {" +"  if (typeof receiveData === 'function') {" +"    receiveData('%s', '%s');" +"  } else {" +"    console.warn('H5 页面未定义 receiveData 函数');" +"  }" +"})();",safeUsername, safePassword);webView.evaluateJavascript(jsCode, null);}});webView.loadUrl("http://xxx/h5/login");OnBackPressedCallback callback = new OnBackPressedCallback(true) {@Overridepublic void handleOnBackPressed() {if (webView.canGoBack()) {webView.goBack(); } else {setEnabled(false); MainActivity.this.onBackPressed(); }}};getOnBackPressedDispatcher().addCallback(this, callback);float statusBarHeight = getStatusBarHeight();Log.d("MainActivity", "状态栏高度: " + statusBarHeight + "px");}private void updateUIForUrl(String url) {if (url.contains("login")) {} else {}}public float getStatusBarHeight() {int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");if (resourceId > 0) {return getResources().getDimension(resourceId);}return 0;}
}
h5页面 接收和传参
<script setup>
import { ref } from 'vue';const username = ref('');
const password = ref('');
function receiveData(u, p) {username.value = u;password.value = p;console.log('接收到数据 - 用户名: ' + u + ', 密码: ' + p);
}
window.receiveData = receiveData;
function sendToAndroid() {if (window.Android) {window.Android.receiveDataFromAndroid('h5向Android发送数据');} else {console.error("Android 接口未注入,可能不在 App 环境");alert("当前不在 App 中,无法调用原生功能");}
}
defineExpose({ receiveData });
</script><template><div><h2>登录页面</h2><p>用户名: {{ username }}</p><p>密码: {{ password }}</p><button @click="sendToAndroid">向 Android 传参</button></div>
</template><style scoped lang="less">
</style>