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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With