Cordova Android插件发送多个回调(进度)

时间:2017-10-05 07:37:37

标签: android cordova cordova-plugins

我正在编写一个自定义插件,它在后面的代码中做了一些重要的事情。我不时会发送进度更新,以便我可以在Ionic中显示它。我在CallbackContext中找不到合适的方法。发送成功回调只能进行一次。如何实现发送进度回调?

private void doHeavyStuff(final CallbackContext callbackContext){

    something.execute(new ResponseHandler() {

            @Override
            public void onProgress(String message) { 
                callbackContext.success(message); //what else ?
            }

            @Override
            public void onFailure(String message) {
                callbackContext.error(message);
            }

            @Override
            public void onSuccess(String message) {
                callbackContext.success(message);
            }
    });
}

1 个答案:

答案 0 :(得分:2)

您可以使用setKeepCallback()来停止在调用时删除的回调实例,允许多次调用它:

public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
    if(action.equals("doHeavyStuff"){
        // Start doing async heavy stuff...

        // Preserve callback
        PluginResult pluginResult = new  PluginResult(PluginResult.Status.NO_RESULT); 
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
        return true;
    }
}

private void doHeavyStuff(final CallbackContext callbackContext){
  something.execute(new ResponseHandler() {
      @Override
      public void onProgress(String message) { 
          PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, message);
          pluginResult.setKeepCallback(true); // keep callback
          callbackContext.sendPluginResult(pluginResult);
     } 

      @Override
      public void onFailure(String message) {
          callbackContext.error(message);
      }

      @Override
      public void onSuccess(String message) {
          callbackContext.success(message);
      }
  });
}