找不到符号addJavascriptInterface

时间:2018-02-27 11:29:26

标签: javascript android cordova

我试图从java脚本获取返回值到Cordova 6.2.0中的java文件。为此我使用以下代码

JavaScriptInterface jsInterface = new JavaScriptInterface(context);
webView.addJavascriptInterface(jsInterface, "JSInterface");
webView.loadUrl("javascript:playVideo('" + something + "')");
public class JavaScriptInterface {
    private Context context;

    public JavaScriptInterface(Context context) {
        this.context = context;
    }

    public void startVideo(String videoAddress){
    }
}
<script>
    window.playVideo = function(video){
        window.JSInterface.startVideo(video);
    }
</script>

当我使用此功能时,我收到错误cannot find symbol addJavascriptInterface,并尝试通过以下解决方案解决此问题

Source 1

public class JavaScriptInterface {
    private Context context;

    @SuppressLint("JavascriptInterface") // I've added this
    public JavaScriptInterface(Context context) {
        this.context = context;
    }

    public void startVideo(String videoAddress){
    }
}

Source 2

WebView wV = (WebView)appView.getEngine().getView();

但我没有得到解决这个问题的方法。任何人都知道如何处理这个...

修改

如源2中所列,我没有appView使用

1 个答案:

答案 0 :(得分:0)

创建Cordova应用时,应使用插件完成java-javascript通信,阅读plugin development guide

在javascript中你称之为java函数:

cordova.exec(successCallback, errorCallback, "videoplayer", "start",["videourl"]);

然后在你的插件java类中添加execute方法

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if ("start".equals(action)) {
        this.startVideo(args.getString(0));
        callbackContext.success();
        return true;
    }
    return false;  // Returning false results in a "MethodNotFound" error.
}

public void startVideo(String videoAddress){
}