如何在后台运行cordova插件?

Tho*_*ten 20 plugins background-process background-thread cordova

我正在制作一个基于phonegap(cordova)的应用程序.我已经测试了一些,最近我在xcode中看到一条消息说"插件应该使用后台线程".那么可以在应用程序的后台运行cordova插件吗?如果是的话,请说明如何.谢谢!

jce*_*ile 28

后台线程与应用程序处于后台时执行代码不同,后台线程用于在执行长任务时不阻止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];
        }];
    }
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)