简体   繁体   English

从Cordova插件的服务调用javascript方法

[英]Call javascript method from Cordova Plugin's service

I am currently developing an App using Cordova and therefore have developed a Cordova Plugin, that runs a service and is being started from within that plugin: 我目前正在使用Cordova开发应用程序,因此开发了Cordova插件,该插件运行一项服务,并从该插件中启动:

  public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
switch(action){
  case "start":
  Intent startIntent = new Intent(context, BackgroundService.class);
  startIntent.putExtra("action", "play");
  context.startService(startIntent);
  return true;
 }
return false;
}

The code is shortened for readability. 缩短了代码的可读性。 Now normally I would use callbacks to call javascript methods from within the plugin, but as I want to use a service for the functionality, how could I call a method (or maybe the callback) from there? 现在,通常我会使用回调从插件中调用javascript方法,但是由于我想使用该功能的服务,如何从那里调用方法(或可能是回调)?

Thank you very much in advance :). 提前非常感谢您:)。

Okay so I did not find a way to this with vanilla cordova, but this Plugin provides the functionality I was looking for: https://github.com/bsorrentino/cordova-broadcaster 好的,所以我没有找到使用香草科尔多瓦的方法,但是此插件提供了我一直在寻找的功能: https : //github.com/bsorrentino/cordova-broadcaster

You have to set up a LocalBroadcastManager in your native Android Code and send an Intent with it. 您必须在本机Android代码中设置LocalBroadcastManager并发送一个Intent。 You then define a bundle containg the data you want to send, and put it as extra of your intent. 然后,您定义一个包含要发送的数据的捆绑包,并将其作为您的附加意图。 Then you send the intent via the broadcast manager and receive it via javascript. 然后,您通过广播管理器发送意图,并通过javascript接收意图。

Sample Java: 示例Java:

  startCallback = new Intent("callback");
  Bundle b = new Bundle();
  b.putString("callback", "start");
  startCallback.putExtras(b);
  LocalBroadcastManager.getInstance(applicationContext).sendBroadcastSync(startCallback);

Sample Javascript: 示例Javascript:

var callbackListener = function( e ) {
       console.log("What kind of callback: " + e.callback);
    };

window.broadcaster.addEventListener( "callback", callbackListener);

I hope this helps somebody with a similiar problem :). 我希望这对遇到类似问题的人有所帮助:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM