Cannot use asynchronous methods in Cordova 3.4. Onsuccess is not called after the first call of plugin method

点点圈 提交于 2019-12-11 03:55:48

问题


Following code does not work properly:

public class TestPlugin extends CordovaPlugin {
   public static CallbackContext callbackContext;

   class TestRun implements Runnable {
      public void run() {
         try {
            Thread.sleep(10000);
         } catch (InterruptedException e) {}

         PluginResult result = new PluginResult(PluginResult.Status.OK, callbackContext.getCallbackId()); 
         result.setKeepCallback(false); 
         callbackContext.sendPluginResult(result); 
      }
   }

   @Override
   public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
      this.callbackContext = callbackContext;
      TestRun tr = new TestRun();
      new Thread(tr).start();
      return true;
   }
}

JS code:

var Test = {
   getBTPrinters: function(successCallback, errorCallback) {
      cordova.exec(successCallback, errorCallback, "TestPlugin", "test", []);
      setTimeout(function(){ cordova.exec(successCallback, errorCallback, "TestPlugin", "test", []); }, 30000);
   }
}

Callback onsuccess in my Javascript code is not called when I call a method from TestPlugin for the first time.
When I call method from this plugin for the second time, then I get onsuccess callback from the first call.
After third call of plugin's method I get onsuccess callback from the second call.
And so on and so forth. Is it a bug of Cordova/Phonegap?
Or I use my plugin in a wrong way?


回答1:


Constantly calling exec will force process the messages.

setInterval(function () {
    cordova.exec(null, null, '', '', [])
}, 200);


来源:https://stackoverflow.com/questions/23934173/cannot-use-asynchronous-methods-in-cordova-3-4-onsuccess-is-not-called-after-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!