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

Kev*_*ede 5 android cordova cordova-plugins

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

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

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

jce*_*ile 5

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

穿线

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

@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;
}
Run Code Online (Sandbox Code Playgroud)

如果您不需要在主界面的线程上运行,但也不想阻塞 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;
}
Run Code Online (Sandbox Code Playgroud)

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都是同步的

  • 这些例子相互矛盾。一个在 UI 线程中调用回调,另一个在工作线程中调用它。你真的告诉我回调发生在哪个线程没有约定吗?通常它不仅仅是一个约定;这将是 `execute(...)` 合约指定的保证。 (2认同)