在模拟器中测试 Xamarin Geofence 原型失败

Testing Xamarin Geofence prototye in emulator fails

我有一个原型应用程序,它使用在 AndroidStudio 中设置的 Geofencing,并且已经能够在 Android 模拟器中成功测试它。因为我需要应用程序也是 iOS 我已将原型移植到 Xamarin/Visual Studio 2017 以确保它在该环境中工作,这样我就可以不必编写应用程序的核心逻辑代码在 Android 和 iOS 中。但是,我无法在同一模拟器上的基于 Xamarin 的应用程序中触发地理围栏。有人在 Xamarin 中使用过这项技术吗? Xamarin 是否需要更改特定设置才能使其正常工作?

问题可能出在清单上。 在 Xamarin 中,当您创建服务(或意向服务)时,应该使用 [Service] 属性对其进行标记,而不是手动将其添加到清单中。

您还应该在处理意图时检查错误(以防您还没有这样做):

[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}");
        }
    }
}

这是我最近做的一个演示(工作)项目:https://github.com/xleon/geofencing-playground