是的,Android 确实在这方面表现出色。
我正在发布我制作的一个随机示例应用程序的示例代码,但这应该会让你继续前进。
让我们首先假设你必须为你的 webview 控制类设置全局变量:
String name = "John";
String lastName = "Doe";
在控制 webview 的 Android 类中(onCreate() 期间或设置 webview 时):
webView.addJavascriptInterface(new JavaScriptInterface(), "android")
你的 webview 控制类的内部类:
/**
* Sets up the interface for getting access to Latitude and Longitude data
* from device
**/
private class JavaScriptInterface {
public String getName() {
return name;
}
public String getLastName() {
return lastName;
}
public void onJavascriptButtonPushed(String text) {
Toast.makeText(WebViewControllingClass.this, "The text of the pressed button is: "+text,Toast.LENGTH_SHORT).show();
}
}
Android 端就是这样,现在通过 Javascript 使用它:
通过 JavaScript 获取姓名和姓氏:
if (window.android){
name = window.android.getName();
lastName = window.android.getLastName();
}
如果你想举杯,请设置一个javascript,其功能是:
if (window.android){
window.android.onJavascriptButtonPushed("Hello");
}
编辑:
我还没有尝试过,但是search 产生了这个,试试吧,它应该可以工作。
如果你想在另一个方向使用它:
JS:
function testEcho(message){
window.JSInterface.doEchoTest(message);
}
安卓:
myWebView.loadUrl("javascript:testEcho('Hello World!')");