将安卓网页视图JS接口方法作为回调函数传递



我有以下安卓代码:

private class MyJavaInterface {
@android.webkit.JavascriptInterface
public void call(String number) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + number));
startActivity(intent);
}
}
...
mWebView.addJavascriptInterface(new MyJavaInterface(), "MyInterface");

此 JS 代码工作正常:

MyInterface.call(number);

这不会:

var call = MyInterface.call;
call(number);

我做错了什么?

此 JS 代码工作正常:

我的界面呼叫(号码(;

是的,这将正常工作,因为Android会自动找到该类和唯一被注释的公共方法。

对于您的情况

MyInterface.call(number) -> new MyJavaInterface().call(number)

但是第二个是行不通的,

MyInterface.call -> new MyJavaInterface().call - there is no public variable in your class and also there is no support for variable in addJavascriptInterface

注:参考

对于面向API 级别 JELLY_BEAN_MR1及更高级别的应用程序,仅 用JavascriptInterface注释的公共方法可以是 从 JavaScript 访问。对于面向 API 级别的应用程序JELLY_BEAN或以下,所有公共方法(包括继承的方法( 可以访问

最新更新