How can I start a background task that implements IBackgroundTask
in a universal app for windows/windows phone?
I am using cordova to create an app for ios, android, wp8 and windows. Each platform seems to run a native class before the application starts, so you can add code here to start a task/service. When a windows project is created by cordova, it is created as a javascript project so there is no c# file to start with.
Is my only option to add winJs
code to start the background task?
In the end, i got round this by creating it as a cordova plugin. So my plugin has a method called init, which i call when the app starts up. Using the plugin, i can call services in iOS, Android or Windows.
Once i created the plugin, i then started my windows service from within the WindowProxy.js file, which is part of the cordova plugin.
Note, that your service itself must be in a separate Library, and that library must have the output type set as Windows Runtime Component.
Sample code to start the service is as follows
Code in WindowsProxy.js file
init: function (successCallback, errorCallback) {
var taskRegistered = false;
var taskName = "Your Background Task Name";
var background = Windows.ApplicationModel.Background;
var iter = background.BackgroundTaskRegistration.allTasks.first();
// check if service already started
while (iter.hasCurrent) {
var task = iter.current.value;
if (task.name === taskName) {
taskRegistered = true;
break;
}
iter.moveNext();
}
if (taskRegistered) {
successCallback();
} else {
Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync().then(function () {
var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
builder.name = taskName;
builder.taskEntryPoint = "CordovaApp.Library.UploadTask"; // namespace of my windows runtime component library
builder.setTrigger(new Windows.ApplicationModel.Background.TimeTrigger(15, false));
builder.addCondition(new Windows.ApplicationModel.Background.SystemCondition(Windows.ApplicationModel.Background.SystemConditionType.internetAvailable));
return builder.register();
}).done(function () {
successCallback();
}, function (err) {
errorCallback(err);
});
}
},