How to stop a Duration based Backgroundservice?

Maybe I'm misunderstanding something of how the background services and watchfaces work, but here's what I gathered:
- The order in which the background service calls functions is this:
AppBase::onStart
AppBase::getServiceDelegate
BackGroundService::initialize
BackgroundService::onTemporalEvent
AppBase::onStop

So the AppBase's onStart and onStop functions are called every time the service runs.
I'm assuming that when the user switches from the watchface to something else (flicking up-down to other widgets, starting activity, etc.) the AppBase onStop would be called, but how am I supposed to differentiate between a call from the background service and the foreground?
I'd like to call Background.deleteTemporalEvent(); in onStop() so that when the watchface is not active the background service does not run.
And when the watchface starts again, I would just start it with Background.registerForTemporalEvent(new Time.Duration(5 * 60));
  • Initailize(), onStart() and onStop run when the main app runs, and each time the background runs.

    If you want to see if onStop is in the main process or the background, set a global like
    var isBackground=false;

    and then in the background process,
    isBackground=true;

    then in onStop you can see if you are in the main process or the background.
    function onStop(state) {
    if(isbackground) {
    } else {
    }
    }


    Globals are not shared between the main process and the background. they are only global to the specific process.
  • Another note, is that watchfaces, as long as yours is the active WF, the temporal event runs. That's by design, so if you are doing something else, the data can be collected by the background. For example, you can get new weather data even if you are recording an activity, and it will be fresh when you go back to the watch face. There are things you can do to handle the background running multiple times when the foreground hasn't run.
  • Ahh.. that's a neat trick, I always forget about global variables. Though this would not work for onStart, but for my case this is good enough. Thank you.

    (I wanted to answer yesterday, but I have serious issues logging into my garmin account. In the last couple of weeks it mostly just does not work.)