JavaScript 调用 Android 方法通常是在混合应用开发中实现的,例如使用 Cordova 或 React Native 这样的框架。以下是一些基础概念和相关信息:
@JavascriptInterface
注解的方法可以被 JavaScript 调用。window.location
来调用原生方法。以下是一个简单的例子,展示如何在 Android 中通过 WebView 实现 JavaScript 调用原生方法:
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
// 添加 JavaScript 接口
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
// 加载本地 HTML 文件
webView.loadUrl("file:///android_asset/index.html");
}
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();
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
</head>
<body>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
</body>
</html>
Uncaught TypeError: Android.showToast is not a function
原因: 可能是因为 addJavascriptInterface
没有正确设置,或者 WebView 没有启用 JavaScript。
解决方法: 确保 WebSettings.setJavaScriptEnabled(true);
已经调用,并且 addJavascriptInterface
已经正确添加了接口。
原因: 使用 @JavascriptInterface
可能会导致安全问题,特别是在 Android 4.2 以下的版本中。
解决方法: 确保只在支持的 Android 版本上使用 @JavascriptInterface
,并且避免在接口方法中执行敏感操作。
通过上述方法,可以在 JavaScript 和 Android 原生代码之间建立有效的通信桥梁。
领取专属 10元无门槛券
手把手带您无忧上云