Is anyone actually using the geofence plugin in production?

ThorvaldBoeThorvaldBoe NOMember ✭✭

I have created an app that uses the geofence plugin (https://github.com/domaven/xamarin-plugins/tree/master/Geofence) to notify users when they enter/exit certain locaitons.

It works to some extent, but there are a few problems:
-When monitoring location exit, iOS users experience numerous false exit notifications, especially when moving around inside the location perimeters. Also if moving outside the location, when phone wakes up after being inactive, one can get 3-4 notifications about exiting the location, even if the user is far away
-All proper exit notifications (not the fake ones) are displayed twice on iOS
-On Android, some users don't get notifications at all, especially if the app is in background or closed

I am thinking about moving to the acr geofencing plugin (https://github.com/aritchie/geofences/tree/master/), but it is a bit of work. So I am wondering if:

1.Does anyone else have experience with either of these plugins in production?
2.Anyone else have experience with same problems that I am facing?

It's weird that nobody else seems to have problems. I was a newbie to Xamarin when writing the app, I am thinking of creating a small sample. Maybe I have made mistakes, although I have been going through my code several times without finding any. Maybe nobody is actually using the geofence plugin for other than playing around....

Appreciate any insights on this.

Answers

  • seanydaseanyda GBMember ✭✭✭✭✭

    How big are the geofences that you've created if you don't mind me asking? I've never used the plugins myself but I know that the location returned can be inaccurate.

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    The geofences are typically 100-200m in radius, sometimes more.
    I've tried even smaller ones, but they tend to get difficult below 50m radius.
    On iOS there are no problems entering the geofence, I get notifications every time. The problem is related to staying within the geofence, which results in lots of fake exit notifications. I also use the highest accuracy.
    I've never thought of the fences being too small, since the entry seems to work fine and being very precise. But it should be easy to test with a much larger fence.
    The problem seems to be related to the app going in the background/sleep mode, my gut feeling says it could be an obscure bug in the plugin. Would be nice to know if I'm the only one experiencing this (which would imply a programming error on my part) or if this is common (which would imply a bug in plugin or in iOS)

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    This is really frustrating.
    I first implemented a small sample app using the (https://github.com/domaven/xamarin-plugins/tree/master/Geofence) plugin. I get every exit notification twice, even in the simulator, so clearly there is at least one bug in there. I did not manage to reproduce the other bug (fake exit notifications) but I suspect that can be device only bug.

    Then I downloaded the acr plugin (https://github.com/aritchie/geofences/tree/master/) and created a small sample app, just to find that it did not give me any notifications at all. The sample code on github and in the solution does not help me, and I am unable to find samples anywhere else.

    Does anyone know about a plugin that actually works?
    I'm looking at writing my own geofencing code for iOS and Android from scratch, which seems like a daunting task.
    Unless somebody can tell me if they have seen these plugins actually work and give me some helpful hints.

  • AllanRitchieAllanRitchie CAInsider, University ✭✭✭

    I haven't had any issues with my geofence plugin. Did you request the necessary permissions for GPS? Was the issue on iOS, Android, or both?

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    Hi Alan, thanks for getting back to me!

    I was trying with iOS, but I will also try on Android. I had no problems setting up a simple sample based on the readme, but I was not able to get any notifications. When you mention it, it could very well be that I am missing some permissions. Here are the permissions I set up in info.plist, just copied from another app using the other geofence plugin (which works, but seems to have issues):

    <key>NSLocationAlwaysUsageDescription</key>
    <string>Appen trenger tilgang til å hente din posisjon</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Appen trenger tilgang til å hente din posisjon</string>
    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>Dersom geo-varsling skal fungere må appen kunne se hvor du er selv når den ikke er i bruk</string>
    

    Here is the code I use to set up the geofence:

    private void Button_Clicked(object sender, EventArgs e)
        {
            //CrossGeofences.Current.StopAllMonitoring();
    
            GeofenceRegion region = new GeofenceRegion("Apple headquarter", new Position(37.332273, -122.03077), Distance.FromKilometers(1));
            CrossGeofences.Current.StartMonitoring(region);
    
            CrossNotifications.Current.Send(new Notification
            {
                Title = "Starting geofencing...",
                Message = "Testing"
            });
        }
    

    And here is the notification code, that I put in OnStart:

        protected override void OnStart()
        {
            base.OnStart();
    
            CrossGeofences.Current.RegionStatusChanged += (sender, args) =>
            {
                var msg = $"Geofence status for {args.Region.Identifier} changed to {args.Status}";
                CrossNotifications.Current.Send(new Notification
                {
                    Title = "Geofence Update",
                    Message = msg
                });
            };
        }
    

    I then tested using the simulator, by switching location between Apple and a custom location far away.
    Thinking of it, I probably need to ask permission to send notifications, that might be part of the problem.

    But still, I was never able to enter the RegionStatusChanged section. Do you see any obvious mistakes?

    I am thinking it could be
    a) Problem related to the simulator - maybe I need to test on physical device? The other plugin works with simulator, however
    b) Problem related to coordinates, somehow the coordinates entered does not enter geofence
    c) Problem with missing permissions
    d) Other stupid error on my part

    I am very happy you replied, I would love to get your plugin working, that would save me a lot of work!

    Cheers,
    Thorvald

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    It's working!
    I added the Plugin.Permissions and Xam.Plugin.Geolocator and checked for location permission and asked for it if missing (not sure if the Geolocator plugin is actually necessary)

    I struggled a bit with plugin versioning, as I had gotten some exceptions, but in the end it turned out to work with latest stable version of all the plugins (duh..!) including xamarin forms (3.1.0.583944)

    Now I am able to trigger RegionStatusChanged event. Have not tried the notifications yet, but hopefully I will get that working too.

    I suppose what did the trick, was asking the location permission. This would be helpful to include in the readme (friendly suggestion :) )

    I have one final question though, in the other plugin we have the concept of a "persistent" region, meaning you will get notifications even if the app is closed. This seems to be out of the box in iOS, on Android it is implemented using a background service. Does your plugin support such "persistent" regions as well? It would be helpful, but it is not critical. I suppose I will find out soon enough on my own.

    Anyway, thanks A LOT, Alan, for asking a small but crucial question, setting me on the right path! You have probably saved me a week of work. Hopefully I can complete my task now, and get it working on both Android and iOS.

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @AllanRitchie said:
    I haven't had any issues with my geofence plugin. Did you request the necessary permissions for GPS? Was the issue on iOS, Android, or both?

    @AllanRitchie, I am able to trigger RegionStatusChanged events while the app is in the foreground, but not when the app is in the background or closed.

    The whole point of my app is to get a notification when you enter/exit a region, also when the app is in the background, or even closed. Is this how the plugin is supposed to work?

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    Sorry, my bad. Got it working now. As it turned out, the region status changed event was triggering all the time, but there was an issue with displaying the notifications that prevented any notifications from being shown. With that fixed, I was able to make it work.

  • NapoleonJonesNapoleonJones USMember

    @ThorvaldBoe Were you able to get this working in the background when the app is closed? I am about to implement a geofencing feature in the app I am building and I need it to run when the app is closed. Is there a specific setting I need to set?

    Thanks in advance.

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @NapoleonJones said:
    @ThorvaldBoe Were you able to get this working in the background when the app is closed? I am about to implement a geofencing feature in the app I am building and I need it to run when the app is closed. Is there a specific setting I need to set?

    Thanks in advance.

    I suppose you are talking about Android, since on iOS it seems to be working out of the box.
    For Android, I ended up writing my own simple geofence plugin that uses the android geofence api (the google play one). The reason for this, is that the aritchie plugin is using the classic android location api to track geofence events, which I suspect will use a lot of battery, and probably not work while the app is closed. The domaven plugin is using the geofence api and works when the app is closed, but is much more complicated than I need, and has proven itself buggy on the iOS part.

    To make the app display geofence notifications when the app is closed, you probably need to implement a background service. This is how the domaven plugin has done it, and that part seems to work. I have not implemented that in my plugin yet, since it is not a critical requirement for me, but I will probably end up doing it at some point. You can study the code of the domaven plugin to see how they do it - I am not able to fully connect all the dots on how it works, but it seems doable.

    I can post here if I am able to implement it.

  • AllanRitchieAllanRitchie CAInsider, University ✭✭✭

    My geofence plugin does work in the background if you set a sticky service. Also, it pulls at a low interval of 200m so it doesn't hit the battery hard of all.

    Lastly, I already have a beta that replaces this mechanism with the standard geofence APIs in 3.0-beta1

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @AllanRitchie said:
    My geofence plugin does work in the background if you set a sticky service. Also, it pulls at a low interval of 200m so it doesn't hit the battery hard of all.

    Lastly, I already have a beta that replaces this mechanism with the standard geofence APIs in 3.0-beta1

    Ok, I will check out your beta plugin. Any idea when it will GA?

    For all us newbies, it would be a tremendous help if you posted a simple, working sample demonstrating the basic use of the plugin, along with the mentioned sticky service. Just sayin... ;);)

  • AllanRitchieAllanRitchie CAInsider, University ✭✭✭
    The new plugin will GA when it’s done.

    Also, I do have a simple working sample in the github repository. There are lots of thing I could do in my sample, but I do this in my free time and the plugin works fine for me, so I’m not working on updating anything at this time. People are welcome to contribute from the community... just sayin.
  • KrunalBerawalaKrunalBerawala USMember ✭✭

    @ThorvaldBoe Can you help with the sample code related to geofence, I am trying to develop a similar feature in my app.

    Thanks

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @KrunalBerawala said:
    @ThorvaldBoe Can you help with the sample code related to geofence, I am trying to develop a similar feature in my app.

    Thanks

    If you want help, you should perhaps put in a little more effort... what do you need help with? What have you tried? What are the features of your app?

  • KrunalBerawalaKrunalBerawala USMember ✭✭

    @ThorvaldBoe I have implemented as per instructions and it works when then app is in foreground. But somehow its not reliable. Sometimes even though device is in the geo fence area, it show device is not in the area. I dont have confidence in putting the app to production. I need help with background implementation of the geofence. my app tailors the data based correct detection of the location.

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @KrunalBerawala said:
    @ThorvaldBoe I have implemented as per instructions and it works when then app is in foreground. But somehow its not reliable. Sometimes even though device is in the geo fence area, it show device is not in the area. I dont have confidence in putting the app to production. I need help with background implementation of the geofence. my app tailors the data based correct detection of the location.

    Are you using the aritchie plugin or the domaven one? Or are you adressing the native api's directly?
    Does the issue occur on iOS, Android or both?

    The domaven plugin seems to be buggy, producing lots of fake notifications on ios. The aritchie one seems ok, but I ended up writing my own in order to utilize the geofence api for android, and to be able to tailor the functionality to my needs. I am starting to get more reliable behavior, but I am still facing intermittent problems like today, when I suddenly stopped getting notifications at all on android. After restarting the phone it started working again. I guess working with Xamarin means you have to accept these kinds of weird issues from time to time.

  • @ThorvaldBoe Puedes ayudar con el código de muestra relacionado con Geofence, estoy intentando desarrollar una característica similar en mi aplicación.

    Las requerimientos son: que me muestre true o false si está adentro o afuera de la Geofence, y mandar un mensaje de notificación.
    Gracias.

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @JuanRodriguez.0823 said:
    @ThorvaldBoe Puedes ayudar con el código de muestra relacionado con Geofence, estoy intentando desarrollar una característica similar en mi aplicación.

    Las requerimientos son: que me muestre true o false si está adentro o afuera de la Geofence, y mandar un mensaje de notificación.
    Gracias.

    I'm sorry, but I don't speak spanish.

  • @ThorvaldBoe You can help with the test code related to Geofence, I am trying to develop a similar feature in my application.

    The Requirement: to show me true or false if it is inside or outside the Geofence, and send a notification message.

    and excuse me if I do not write English well.
    Thank you

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @JuanRodriguez.0823 said:
    @ThorvaldBoe You can help with the test code related to Geofence, I am trying to develop a similar feature in my application.

    The Requirement: to show me true or false if it is inside or outside the Geofence, and send a notification message.

    and excuse me if I do not write English well.
    Thank you

    What did you try so far? Did you run into a problem?

  • antsaantsa Member ✭✭

    Hello!
    I am developing an application using Windows.Forms
    My application shows a notification when a user enters or exits a zone.
    I use:
    Xamarin.Forms 3.1.0.583944
    Plugin.Geofencing 2.0.0
    Plugin. Permissions 2.2.1
      
    My application works fine when it is active or in the background. But it does not work when the application is closed. I reboot my phone and notifications do not come.
    I need the notifications to work even when the application is closed. How can I do that?

    The problem occurs only in Android, everything works in iOS.

  • ThorvaldBoeThorvaldBoe NOMember ✭✭

    @antsa said:
    Hello!
    I am developing an application using Windows.Forms
    My application shows a notification when a user enters or exits a zone.
    I use:
    Xamarin.Forms 3.1.0.583944
    Plugin.Geofencing 2.0.0
    Plugin. Permissions 2.2.1
      
    My application works fine when it is active or in the background. But it does not work when the application is closed. I reboot my phone and notifications do not come.
    I need the notifications to work even when the application is closed. How can I do that?

    The problem occurs only in Android, everything works in iOS.

    I suppose you mean Xamarin.Forms (not windows...) :)

    Plugin.Geofencing is the ACR plugin I believe. As @AllanRitchie says, you can implement this behaviour by using a sticky service, although I don't have enough experience with Android to tell you exactly how to do that.

  • antsaantsa Member ✭✭

    I suppose you mean Xamarin.Forms (not windows...) :)

    Yes :)

    you can implement this behaviour by using a sticky service

    What is sticky service? Are there code samples or a library?

  • antsaantsa Member ✭✭

    Done! Now when the application is closed, the event is triggered.

    Service:

     [Service]
        public class DeepBackgroundService : Service
        {
            static readonly string TAG = typeof(DeepBackgroundService).Name;        
            public override IBinder OnBind(Intent intent)
            {
                return null;
            }
            public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
            {
                return StartCommandResult.Sticky;
            }
            public override void OnCreate()
            {
                base.OnCreate();
                CrossGeofences.Current.RegionStatusChanged += (sender, args) =>
                {
                    if (args.Status == GeofenceStatus.Entered)
                    {
                // code
                    }
                    if (args.Status == GeofenceStatus.Exited) 
                    {
                // code
                    }
                };
            }
        }
    

    Service start:

        protected override void OnCreate(Bundle bundle)
                {
                // ...
                StartService(new Intent(this, typeof(DeepBackgroundService)));
                // ...
            }
    
  • antsaantsa Member ✭✭

    But, after rebooting, the phone service does not work. How to start the service after rebooting the device?

  • antsaantsa Member ✭✭

    Done!

    [assembly: UsesPermission(Name = "android.permission.RECEIVE_BOOT_COMPLETED")]
    namespace MyApp.Droid
    {
    [BroadcastReceiver(Enabled = true, Exported = true)]
        [IntentFilter(new[] { Intent.ActionBootCompleted }, Priority = (int)IntentFilterPriority.HighPriority)]
        public class GeofenceBootUpReceiver : BroadcastReceiver
        {
            public override void OnReceive(Context context, Intent intent)
            {
                var restartServiceIntent = new Intent(Application.Context, typeof(DeepBackgroundService));
                restartServiceIntent.SetPackage(Application.Context.PackageName);
                PendingIntent restartServicePendingIntent = PendingIntent.GetService(Application.Context, 3, restartServiceIntent, PendingIntentFlags.OneShot);
                AlarmManager alarmService = (AlarmManager)Application.Context.GetSystemService(Context.AlarmService);
                alarmService.Set(
                    AlarmType.RtcWakeup,
                    SystemClock.CurrentThreadTimeMillis() + 1000,
                    restartServicePendingIntent);
            }
        }
    }
    
  • MarcoPuccioMarcoPuccio USMember

    Hello everybody.
    I'm developing a small APP with the Geofences feature CrossGeeks/GeofencePlugin.

    On android everything works well, while with iOS (Iphone 7 plus iOS 13.2.3) when I activate monitoring for all regions, the OnRegionStateChanged method is called for all regions even if they are out of the fence.

    Do you know how to solve?
    Thanks

  • ShamnadShamnad USMember ✭✭✭
    edited January 22

    @ThorvaldBoe am trying to develop an app which is having the same use case . need to get the user a notification when he going outside from the geofence. I have installed the Plugin.Permissions and Xam.Plugin.Geolocator .
    below are the code with i done so far.
    ` public class CrossGeofenceListener : IGeofenceListener
    {
    private ErrorReportService _database = new ErrorReportService();

        public void OnMonitoringStarted(string region)
        {
            Debug.WriteLine(string.Format("{0} - Monitoring started in region: {1}", CrossGeofence.Id, region));
        }
    
        public void OnMonitoringStopped()
        {
            Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, "Monitoring stopped for all regions"));
        }
    
        public void OnMonitoringStopped(string identifier)
        {
            Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Monitoring stopped in region", identifier));
        }
    
        public void OnError(string error)
        {
            Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Error", error));
        }
    
        // Note that you must call CrossGeofence.GeofenceListener.OnAppStarted() from your app when you want this method to run.
        public void OnAppStarted()
        {
            Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, "App started"));
        }
    
        public async void OnRegionStateChanged(GeofenceResult result)
        {
            if (result != null)
            {
                Debug.WriteLine(string.Format("{0} - {1} - {2}", CrossGeofence.Id, result.RegionId, result.TransitionName));
                await _database.SaveLog(LoggingType.SystemsLog, this.ToString(), result.TransitionName).ConfigureAwait(false);
    }
        }
    
        public async void OnLocationChanged(GeofenceLocation location)
        {
            if (location != null)
            {
                await _database.SaveLog(LoggingType.SystemsLog, this.ToString(), location.Latitude.ToString()).ConfigureAwait(false);
            }
        }
    }`
    

    and in the view model

              ` CrossGeofence.GeofencePriority = GeofencePriority.HighAccuracy;
                CrossGeofence.Current.StartMonitoring(new GeofenceCircularRegion("MY location", 100.4567, 7630559, 5, true)
                {
                    NotifyOnStay = true,
                    StayedInThresholdDuration = TimeSpan.FromSeconds(2),
                    ExitThresholdDuration = TimeSpan.FromSeconds(2),
                    ShowExitNotification = true,
                    ShowNotification = true,
                    ShowStayNotification = true,
                    NotifyOnExit = true,
                    NotifyOnEntry = true,
                    NotificationExitMessage = "exit",
                    NotificationStayMessage = "exist on the same location",
                });`
    

    what else i have to do for ios.

    am getting the notification when i load the page. what is the correct implementation for getting the notification background. where we can do our logic in this plugin. i need make the user offline when user exit from the fence

Sign In or Register to comment.