Hi, I am working on a background web request for a watch face. I have read various discussions here on this but nothing that solves my issue.
I include full test code simplified as far as possible (it's only 90 lines) - when the temporal event is fired in the simulator the web request is made and successfully returns a result. When Background.exit is then called, onBackgroundData is not called.
I thought it easier to show the full code rather than explaining further what I do and don't do. As a test line 74 can be uncommented (this does fire onBackgroundData, but without the web request result so is useless) I am using VSCode.
Thanks for any insights anyone may have...
Full file litdev.uk/stuff/bgwfApp.mc - can't update in this slightly weird forum.
using Toybox.Application as App;
using Toybox.Background;
using Toybox.System as Sys;
using Toybox.WatchUi as Ui;
using Toybox.Graphics as Gfx;
using Toybox.PersistedContent;
using Toybox.Lang as Lang;
var inBackground = false;
var _myResult = -1;
(:background)
class bgwfApp extends App.AppBase {
function initialize() {
AppBase.initialize();
}
// onStart() is called on application start up
function onStart(state) {
Sys.println("onStart");
}
// onStop() is called when your application is exiting
function onStop(state) {
if (!inBackground) {
Sys.println("onStop !inBackground");
} else {
Sys.println("onStop");
}
}
// Return the initial view of your application here
function getInitialView() {
Sys.println("getInitialView");
if (Toybox.System has :ServiceDelegate) {
Background.registerForTemporalEvent(new Time.Duration(5 * 60));
} else {
Sys.println("****background not available on this device****");
}
return [new bgwfView()];
}
function onBackgroundData(data) {
Sys.println("onBackgroundData=" + data);
_myResult = data;
Ui.requestUpdate();
}
function getServiceDelegate() {
Sys.println("getServiceDelegate");
return [new BgbgServiceDelegate()];
}
function onAppInstall() {
Sys.println("onAppInstall");
}
function onAppUpdate() {
Sys.println("onAppUpdate");
}
}
(:background)
class BgbgServiceDelegate extends Toybox.System.ServiceDelegate {
function initialize() {
Sys.ServiceDelegate.initialize();
inBackground = true; //trick for onExit()
}
function onTemporalEvent() {
getMyData();
Sys.println("onTemporalEvent");
_myResult = 0;
//Background.exit(_myResult); // This fires onBackgroundData, but obviously doesn't do the web request!
}
private function getMyData() as Void {
var options = {
:responseType => Communications.HTTP_RESPONSE_CONTENT_TYPE_JSON,
:headers => {
"Content-Type" => Communications.REQUEST_CONTENT_TYPE_URL_ENCODED,
},
};
Communications.makeWebRequest(
"https://jsonplaceholder.typicode.com/todos/115",
null,
options,
method(:onReceive)
);
}
