我正在基于PhoneGap(Cordova)制作应用程序。我已经进行了一些测试,最近在Xcode中看到了一条消息,上面写着“插件应使用后台线程”。那么,是否可能使Cordova插件在应用程序的后台运行?如果可以,请告诉我如何操作。谢谢!
我正在基于PhoneGap(Cordova)制作应用程序。我已经进行了一些测试,最近在Xcode中看到了一条消息,上面写着“插件应使用后台线程”。那么,是否可能使Cordova插件在应用程序的后台运行?如果可以,请告诉我如何操作。谢谢!
后台线程并不等同于应用程序在后台执行代码,后台线程用于在执行长时间任务时不阻塞UI。
iOS上的后台线程示例
- (void)myPluginMethod:(CDVInvokedUrlCommand*)command
{
// Check command.arguments here.
[self.commandDelegate runInBackground:^{
NSString* payload = nil;
// Some blocking logic...
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload];
// The sendPluginResult method is thread-safe.
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
Android后台线程的示例
@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;
}
commandDelegate.run(inBackground: { [self] in
callingMethod()
})