23

我正在制作基于 phonegap (cordova) 的应用程序。我已经测试过几次,最近我在 xcode 中看到一条消息说“插件应该使用后台线程”。那么是否可以让cordova插件在应用程序的后台运行呢?如果是这样,请告诉如何。谢谢!

4

1 回答 1

32

后台线程与应用程序在后台执行代码不同,后台线程用于在执行长任务时不阻塞 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;
    }
于 2014-03-14T09:20:41.353 回答