Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run cordova plugins in the background?

Im making an application based on phonegap (cordova). I have tested it some times, and lately I saw a message in xcode that said "Plugin should use a background thread." So is it possible to make cordova plugins run in the background of the app? if so, please tell how. Thanks!

like image 235
Thomas M. Tveten Avatar asked Mar 13 '14 14:03

Thomas M. Tveten


People also ask

How do I run Cordova plugin in my browser?

If you're using Visual Studio Code, go to the Debug tab, enable Cordova debugging, then execute either the Simulate Android in browser or Simulate iOS in browser options. Cordova Simulate will open the Chrome browser and execute the web application part of your Cordova app.


1 Answers

A background thread isn't the same that executing code while the app is in background, a background thread is used to don't block the UI while you execute a long task.

Example of background thread on 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];
        }];
    }

Example of background thread on 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;
    }
like image 157
jcesarmobile Avatar answered Oct 19 '22 01:10

jcesarmobile