Cordova 插件回调使用什么线程?

What thread to use for Cordova plugin callback?

应该在哪个线程中调用 CallbackContext 的方法?

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

如果WebView线程不是UI线程,我应该在WebView线程中回调,是否可以异步进行?

我把 android 插件文档的线程部分给你了。 这些插件都是异步的,当你调用它们时,你会得到一个成功或失败的回调。如果本机任务太长,theads 只是为了不阻塞 UI。

Threading

The plugin's JavaScript does not run in the main thread of the WebView interface; instead, it runs on the WebCore thread, as does the execute method. If you need to interact with the user interface, you should use the following variation:

@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;
}

Use the following if you do not need to run on the main interface's thread, but do not want to block the WebCore thread either:

@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

凯文的笔记:

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