4
votes

I'm trying to implement geofencing in Windows phone 8.1. First I wanted to create a sample Project to understand how it Works, but i couldnt make it works. What I'm trying to achieve is basically, I'll set the coordinates and close the app by pressing back button and it will trigger a toast notification when the phone is in the area of interest.

I've created a blank Windows phone(silverlight) 8.1 Project(geofence_test_01) and added a Windows RT Component Project(BackgroundTask) into the same solution. Added a reference for BackgroundTask in the geofence_test_01 Project.

Solution Explorer

ID_CAP_LOCATION is enabled in the app manifest.

WMAppManifest.xml

MainPage.xaml has only one button to start geofencing.

<Button Name="btnStart" Content="Start" Click="btnStart_Click"/>

In btnSave_Click, I call a method which creates the geofence and registers the background task.

private void btnStart_Click(object sender, RoutedEventArgs e)
    {
        Init_BackgroundGeofence();
        registerBackgroundTask();  
    }

private async Task Init_BackgroundGeofence()
        {
            //----------------- Crating Geofence ---------------
            var geofenceMonitor = GeofenceMonitor.Current;
            var geoId = "building9";
            var positionBuilding9 = new BasicGeoposition()
            {
                Latitude = 47.6397,
                Longitude = -122.1289
            };
            var geofence = new Geofence(geoId, new Geocircle(positionBuilding9, 100),
                MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited,
                false, TimeSpan.FromSeconds(10));
            geofenceMonitor.Geofences.Add(geofence);
        }

private async Task registerBackgroundTask()
    {
        //----------------- Register Background Task ---------------
        var backgroundAccessStatus =
            await BackgroundExecutionManager.RequestAccessAsync();
        var geofenceTaskBuilder = new BackgroundTaskBuilder
        {
            Name = "GeofenceBackgroundTask",
            TaskEntryPoint = "BackgroundTask.GeofenceBackgroundTask"
        };

        var trigger = new LocationTrigger(LocationTriggerType.Geofence);
        geofenceTaskBuilder.SetTrigger(trigger);
        var geofenceTask = geofenceTaskBuilder.Register();
    }

And finally, in BackgroundTask, I've the following code:

namespace BackgroundTask
{
    public sealed class GeofenceBackGroundTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var geofenceMonitor = GeofenceMonitor.Current;
            var geoReports = geofenceMonitor.ReadReports();
            var geoId = "building9";
            foreach (var geofenceStateChangeReport in geoReports)
            {
                var id = geofenceStateChangeReport.Geofence.Id;
                var newState = geofenceStateChangeReport.NewState;
                if (id == geoId && newState == GeofenceState.Entered)
                {
                  //------ Call NotifyUser method when Entered -------
                    notifyUser(); 
                }
            }
        }

        private void notifyUser()
        {
            var toastTemplate = ToastTemplateType.ToastText02;
            var toastXML = ToastNotificationManager.GetTemplateContent(toastTemplate);
            var textElements = toastXML.GetElementsByTagName("text");
            textElements[0].AppendChild(toastXML.CreateTextNode("You are in!"));

            var toast = new ToastNotification(toastXML);

            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
    }
}

I get no error when building and deploying this in the emulator. I set a breakpoint in the backgroundTask but I've not seen that part of code is called yet. It never hits the breakpoint. I test it by using Additional Tools of the emulator, in Location tab, by clicking somewhere in my geofence area on the map, waiting for a while, but it never hits the breakpoint. Hope somebody can tell me what i am missing here...

I've checked these following links to build this application:

http://www.jayway.com/2014/04/22/windows-phone-8-1-for-developers-geolocation-and-geofencing/

Geofence in the Background Windows Phone 8.1 (WinRT)

Toast notification & Geofence Windows Phone 8.1

http://java.dzone.com/articles/geofencing-windows-phone-81

Thanks

You can download the project here: https://drive.google.com/file/d/0B8Q_biJCWl4-QndYczR0cjNhNlE/view?usp=sharing

---- Some clues

Thanks to Romasz, I've checked the Lifecycle events and i see "no background tasks" even after registerBackgroundTask() is executed.... Apparently there is something wrong/missing in registerBackgroundTask() method.

2
Have you checked if the BTask is registered. If it's registered, have you tried to fire it through Lifecycle events tab? Also what for is this CoreWindow in BTask? - the task runs in background so you won't have CoreWindow, you can send toast without using dispatcher.Romasz
@Romasz , appearently background task is not being registered even after the registerBackgroundTask() method is called. Because when i run the app in debug mode, i see "No Background Task" in Lifecycle Events. There must be something missing in this method. --- Btw, i've removed the dispatcher form background task. thnx for the advice.Emrah Ozbekar
Is it possible that you share the sample project?Romasz
@Romasz i've just added the link at the end of my question.Emrah Ozbekar
@Romasz, there is method call commented out in Start_Click for "Init_Geofence()". If I uncomment it, i see the gefence is working in the foreground. I can see the message "Welcome to Building 9!". You can see the screenshot here: oi60.tinypic.com/nqr52o.jpgEmrah Ozbekar

2 Answers

0
votes

I've tried to build my sample (it was easier for me to build a new one) basing on your code and it seems to be working. You can take a look at it at my GitHub.

There are couple of things that may have gone wrong in your case:

  • remember to add capabilities in WMAppManifest file (IS_CAP_LOCATION) and Package.appxmanifest (Location)
  • check the names (of namespaces, classes and so on) in BackgroundTask
  • check if your BackgroundTask project is Windows Runtime Componenet and is added to your main project as a reference

I know you have done some of this things already, but take a look at my sample, try to run it and maybe try to build your own from the very beginning.

0
votes

Did you add your background task in the Package.appxmanifest under Declarations with the correct supported task types (Namely Location)?enter image description here