Search code examples
androidxamarinandroid-geofence

Testing Xamarin Geofence prototye in emulator fails


I have a prototype application that uses Geofencing set up in AndroidStudio and have been able to succesfully test it in the Android Emulator. Because I need the application to also be iOS i have ported the prototype to Xamarin/Visual Studio 2017 to make sure that it works in that environment so I can save myself from having to code the core logic of the app in Android and iOS. However I am not able to get the Geofences to fire in the Xamarin based app on the same emulator. Has anyone worked with this technology in Xamarin? are there specific settings that need to change for Xamarin to make this work?


Solution

  • The issue is probably coming from the manifest. In Xamarin, when you create a service (or intent service) it should be tagged with the attribute [Service], instead of adding it to the manifest manually.

    You should also check for errors when handling the intent (in case you are not doing it already):

    [Service]
    public class GeofenceTransitionsIntentService : IntentService, IEnableDatabaseLogger
    {
        public GeofenceTransitionsIntentService()
            : base(nameof(GeofenceTransitionsIntentService)) { }
    
        protected override void OnHandleIntent(Intent intent)
        {
            base.OnHandleIntent(intent);
    
            this.Log().Info("Intent received");
    
            var geofencingEvent = GeofencingEvent.FromIntent(intent);
            if (geofencingEvent.HasError)
            {
                var errorMessage = GeofenceErrorMessages.GetErrorString(this, geofencingEvent.ErrorCode);
                this.Log().Error(errorMessage);
    
                return;
            }
    
            var geofenceTransition = geofencingEvent.GeofenceTransition;
            var geofences = geofencingEvent.TriggeringGeofences;
            var location = geofencingEvent.TriggeringLocation;
    
            if (geofenceTransition == Geofence.GeofenceTransitionEnter)
            {
                foreach (var geofence in geofences)
                    this.Log().Info($"Entered {geofence.RequestId} at {location.Latitude}/{location.Longitude}");
    
                // do something
            }
            else if (geofenceTransition == Geofence.GeofenceTransitionExit)
            {
                foreach (var geofence in geofences)
                    this.Log().Info($"Exited {geofence.RequestId} at {location.Latitude}/{location.Longitude}");
    
                // do something
            }
            else
            {
                this.Log().Error($"Geofence transition invalid type: {geofenceTransition}");
            }
        }
    }
    

    Here is a demo (working) project I did recently: https://github.com/xleon/geofencing-playground