在 Android 开发中,我们通常使用 WebView 组件来加载和显示 HTML5 页面。要实现 Android 与 HTML5 的交互,我们需要使用 WebView 提供的 JavaScript 接口。
以下是 Android 与 HTML5 交互的常用方法及示例:
1: Android 调用 HTML5 中的 JavaScript 函数:
在 WebView 中设置 JavaScriptEnabled
为 true
,然后使用 loadUrl()
方法调用 HTML5 中的 JavaScript 函数。
WebView webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); // 加载 HTML5 页面 webView.loadUrl("file:///android_asset/sample.html"); // 调用 HTML5 中的 JavaScript 函数 webView.loadUrl("javascript:alert('Hello from Android')");
复制
2: HTML5 调用 Android 中的方法:
创建一个与 JavaScript 交互的类,并使用 @JavascriptInterface
注解为 HTML5 提供 Android 方法。
示例:
public class WebAppInterface { Context context; WebAppInterface(Context context) { this.context = context; } @JavascriptInterface public void showToast(String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } }
复制
在 WebView 中添加 JavaScript 接口,并设置接口名称:
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
复制
在 HTML5 页面中调用 Android 方法:
<!DOCTYPE html> <html> <head> <title>Sample HTML</title> <script type="text/javascript"> function callAndroidFunction() { Android.showToast("Hello from HTML5"); } </script> </head> <body> <button onclick="callAndroidFunction()">Call Android Function</button> </body> </html>
复制
3: Android 与 HTML5 双向交互:
在 HTML5 页面中添加一个按钮,点击按钮时调用 Android 方法,并在 Android 方法中调用 HTML5 中的 JavaScript 函数。
示例:
HTML5 页面(sample.html):
<!DOCTYPE html> <html> <head> <title>Sample HTML</title> <script type="text/javascript"> function showMessage(message) { alert(message); } </script> </head> <body> <button onclick="Android.callJavaScriptFunction()">Call JavaScript Function</button> </body> </html>
复制
Android 代码:
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); webView.getSettings().setJavaScriptEnabled(true); webView.addJavascriptInterface(new WebAppInterface(this), "Android"); webView.loadUrl("file:///android_asset/sample.html"); } public class WebAppInterface { Context context; WebAppInterface(Context context) { this.context = context; } @JavascriptInterface public void callJavaScriptFunction() { runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl("javascript:showMessage('Hello from Android')"); } }); } } }
复制