What thread to use for Cordova plugin callback?

主宰稳场 提交于 2019-12-04 10:08:08

I put you the Threading section of the android plugins documentation. The plugins are all asynch, when you call them you get a success or failure callback. The theads are just to not block the UI if the native task is too long.

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

Note from Kevin:

Calls to the methods of CallbackContext end up calling CordovaWebView#sendPluginResult(PluginResult cr, String callbackId). The implementation of that method in CordovaWebViewImpl calls NativeToJsMessageQueue#addPluginResult(cr, callbackId), which ultimately results in an element being added to a LinkedList inside a synchronized block. All accesses to that List are synchronized

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