Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What thread to use for Cordova plugin callback?

In what thread are the methods of CallbackContext supposed to be called?

The documentation for CordovaPlugin#execute(...) says it's called in the WebView thread. Is that the same as the UI thread? If so, then that's probably my answer.

If the WebView thread is not the UI thread, and I'm supposed to call back in the WebView thread, is it possible to do so asynchronously?

like image 719
Kevin Krumwiede Avatar asked Mar 11 '15 04:03

Kevin Krumwiede


1 Answers

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

like image 119
jcesarmobile Avatar answered Oct 06 '22 18:10

jcesarmobile