Search code examples
c#alarmbackground-taskwin-phone-silverlight-8.1

Microsoft.Phone.Scheduler.Alarm in a BackgroundTask


I recommend your assistance.

I am using Silverlight 8.1 to program an GPS based alarm app (Because the Microsoft.Phone.Scheduler.Alarm api is blocked in WP 8.1). Now I am trying to create a BackgroundTask triggered by the GeofenceMonitor.

My problem is that a BackgroundTask must be located in a "Windows Runtime Component" project and you can't set the compilation target to Silverlight 8.1, so I cannot create an Alarm in there.

Is there a workaround or is it just impossible to launch an Alarm from a BackgroundTask? I would appreciate every solution.


Solution

  • Unfortunately you cannot mix WinRT and WP8.1 Silverlight.

    As you mentioned the Alarm API doesn't work with WP (so much for "universal") and the Silverlight Runtime doesn't have the GeofenceMonitor. You can have a Silverlight Project with a WinRT background task, but that won't get you anywhere.

    I don't know if you want these alarms permanently associated with a location or rather short-lived, but maybe this would be a solution:

    Configure your app to keep running in the background. There is a dedicated "LocationTracking" Execution Type that you can use for any app that tracks the GPS Position in the background (see this site for details).

    You can then use the PositionChanged event of your Geolocator to check if you are within your fence and add an (almost) instant alarm.

    const string id = "whateverYourIdIs";
    var existing = ScheduledActionService.Find(id);
    if(existing != null)
       ScheduledActionService.Remove(id);
    
    Alarm alarm = new Alarm(id)
    {
       BeginTime = DateTime.Now.AddSeconds(1),
       Content = "You have reached your location!",
    };
    
    ScheduledActionService.Add(alarm);
    

    If you don't want to keep your app running, you could (propably) launch another background task (SL) from within the geo-fencing background task (WinRT).