从本机 java 代码调用 JS 事件

Call JS events from native java code

本文关键字:JS 事件 调用 代码 本机 java      更新时间:2023-09-26

我正在创建一个 cordova 插件,我需要在角度 JS 代码中引发一个自定义事件。

例如,我需要从本机 java 代码调用下面的函数

var callFromJava=function(){
   alert("Call received from Native code");
}

现在我需要从本机代码中的活动中调用它。

更新 1 科尔多瓦文件

public class CordovaApp extends CordovaActivity
{
    super.onCreate(savedInstanceState);
    super.init();
    wv = new CordovaWebView(this);
    Log.i("PARSEPUSH","URL of main "+wv.getUrl());
    // Set by <content src="index.html" /> in config.xml.
    Log.i("PARSEPUSH",launchUrl);
    loadUrl(launchUrl);

   public void callJS(){
      //something goes here to call JS event.
   }
} 

我想使用科尔多瓦loadUrlsendJavascript()方法。我不知道如何使用它们。

 public void callJS() {
    if (this.appView != null) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            appView.stopLoading();
            appView.evaluateJavascript("(function(){return document.location.href;})();", new ValueCallback<String>() {                       @Override
                public void onReceiveValue(String value) {
                    //doSomething for the return value
                }
            });
        } else {
            appView.loadUrl("javascript:alert(document.location.href);");
        }
    }

请参阅此代码片段以查看是否有帮助。这与Codorva Phonegap无关,只是从Java端调用Js。

如果你想写Cordova插件,你可以参考Devgirl的博客,她写了很多关于Phone-gap扩展的优秀文章。