gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:05:06 24 4
gpt4 key购买 nike

CallbackContext的方法在哪个线程中?应该叫什么?

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

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

最佳答案

我给你介绍了 android 插件文档的线程部分。这些插件都是异步的,当你调用它们时,你会得到一个成功或失败的回调。如果 native 任务太长,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 中一个同步块(synchronized block)。对该 List 的所有访问都是同步的

关于android - Cordova 插件回调使用什么线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com