I have created plugin for background service (to run the application in background) in phonegap.
here is my java code for plugin:
public class Backgr
Creation of plugin is fine.You create your service just like a normal java file. And then As soon as you call this plugin . you just start your service like
startService(new Intent(this, MyService.class));
Then your service will run in background.This is an easy way to do.
If separately you create service then
Your Plugin should look like this
public class BackgroundService extends Plugin {
private static final String TAG = "BackgroundService";
private static final String CALL_SERVICE_ACTION = "callService";
@Override
public PluginResult execute(String action, JSONArray args, String callbackId)
{
Log.i(TAG, "Plugin Called");
PluginResult result = null;
if (CALL_SERVICE_ACTION.equals(action)) {
Log.d(TAG, "CALL_SERVICE_ACTION");
startService(new Intent(ctx, MyService.class));
}
else {
result = new PluginResult(Status.INVALID_ACTION);
Log.d(TAG, "Invalid action : " + action + " passed");
}
return result;
}
}
Your .js file should look like this
function BackgroundService() {
};
BackgroundService.prototype.callService = function(successCallback, failCallback) {
return PhoneGap.exec(successCallback, failCallback, "BackgroundService",
"callService", [ null ]);
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin("BackgroundService", new BackgroundService());
});
And your HTML file should look like this
function callServiceFunction() {
window.plugins.BackgroundService.callService('callService',
callServiceSuccessCallBack, callServiceFailCallBack);
}
function callServiceSuccessCallBack(e) {
alert("Success");
}
function callServiceFailCallBack(f) {
alert("Failure");
}
Also you need to register your phonegap plugin in your res/xml/plugins.xml like
<plugin name="BackgroundService" value="package-structure.BackgroundService"/>
In the onCreate method of your Java class that extends from DroidGap make sure you have set "keepRunning" properly.
super.setBooleanProperty("keepRunning", true);