用于Cordova插件回调的线程是什么?

时间:2015-03-11 04:24:00

标签: android cordova cordova-plugins

应该调用CallbackContext的方法是什么线程?

CordovaPlugin#execute(...)的文档说它是在WebView线程中调用的。这与UI线程相同吗?如果是这样,那可能就是我的答案。

如果WebView线程不是UI线程,并且我应该在WebView线程中回调,是否可以异步执行此操作?

1 个答案:

答案 0 :(得分:3)

我给你安装了android插件文档的Threading部分。 这些插件都是异步的,当你调用它们时,你会获得成功或失败的回调。如果本机任务太长,那么theads就是不阻止UI。

  

线程

     

插件的JavaScript不能在WebView的主线程中运行   接口;相反,它在WebCore线程上运行,执行也是如此   方法。如果您需要与用户界面进行交互,则应该   使用以下变体:

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if ("beep".equals(action)) {
        final long duration = args.getLong(0);
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                ...
                callbackContext.success(); // Thread-safe.
            }
        });
        return true;
    }
    return false;
}
  

如果您不需要在主界面上运行,请使用以下命令   线程,但不想阻止WebCore线程:

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if ("beep".equals(action)) {
        final long duration = args.getLong(0);
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                ...
                callbackContext.success(); // Thread-safe.
            }
        });
        return true;
    }
    return false;
}

http://docs.phonegap.com/en/3.5.0/guide_platforms_android_plugin.md.html#Android%20Plugins

Kevin的注释:

调用CallbackContext的方法最终调用CordovaWebView#sendPluginResult(PluginResult cr, String callbackId)。在CordovaWebViewImpl调用NativeToJsMessageQueue#addPluginResult(cr, callbackId)中实现该方法,最终导致元素被添加到同步块内的LinkedList。对List的所有访问都是同步的