registring后台任务时,新的LocationTrigger(LocationTriggerType.Geofence)失败,出现InvalidCastException

时间:2016-05-05 06:11:01

标签: c# windows-phone-8.1 windows-rt windows-locationapi

我使用geofence api和后台任务构建简单的app来处理地理围栏的变化。这是代码的一部分,尝试注册后台任务

private async void RegisterBackgroundTask()
{
    const string name = "GeofenceBackgroundTask";

    if (BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == name))
    {
        return;
    }

    var loc = await new Geolocator().GetGeopositionAsync(
        TimeSpan.FromMinutes(2),
        TimeSpan.FromSeconds(5));   //needed to trig user acceptance

    var backgroundAccessStatus =
        await BackgroundExecutionManager.RequestAccessAsync();

    if (backgroundAccessStatus != BackgroundAccessStatus.Denied)
    {
        var geofenceTaskBuilder = new BackgroundTaskBuilder()
        {
            Name = name,
            TaskEntryPoint = "RingtoneManager.Background.GeofenceBackgroundTask"
        };

        geofenceTaskBuilder.SetTrigger(new LocationTrigger(LocationTriggerType.Geofence));
        geofenceTaskBuilder.Register();
    }
}

这条线总是失败

new LocationTrigger(LocationTriggerType.Geofence)

使用InvalidCastException

System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Unable to cast object of type 'System.__ComObject' to type   'Windows.ApplicationModel.Background.ILocationTriggerFactory'.
Source=mscorlib
StackTrace:
   at System.StubHelpers.StubHelpers.GetCOMIPFromRCW_WinRT(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget)
   at Windows.ApplicationModel.Background.LocationTrigger..ctor(LocationTriggerType triggerType)
   at RingtoneManager3.App.<RegisterBackgroundTask>d__2.MoveNext()
InnerException: 

我尝试注册触发器,这样的系统时间触发器,没有例外。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为你需要先创建geocircle。

public static void CreateGeofence(BasicGeoposition position, double radius, string id = "default")
        {
            // The Geofence is a circular area centered at (latitude, longitude) point, with the
            // radius in meter.
            var geocircle = new Geocircle(position, radius);

        // Sets the events that we want to handle: in this case, the entrace and the exit
        // from an area of intereset.
        var mask = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;

        // Specifies for how much time the user must have entered/exited the area before 
        // receiving the notification.
        var dwellTime = TimeSpan.FromSeconds(1);

        // Creates the Geofence and adds it to the GeofenceMonitor.
        var geofence = new Geofence(id, geocircle, mask, false, dwellTime);

        try
        {
            GeofenceMonitor.Current.Geofences.Add(geofence);
        }
        catch (Exception e)
        {
            //Debug.WriteLine(e);
            // geofence already added to system
        }
    }

然后为每个位置创建地理围栏

CreateGeofence(new BasicGeoposition() { Longitude = double.Parse(VersionObject.store.lng), Latitude = double.Parse(VersionObject.store.lat) }, 200);
                            try
                            {
                                var backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
                                var geofenceBuilder = new BackgroundTaskBuilder
                                {
                                    Name = "Test Geofence",
                                    TaskEntryPoint = "GeofencingTask.BackgroundGeofencing"
                                };
                                var trigger = new LocationTrigger(LocationTriggerType.Geofence);
                                geofenceBuilder.SetTrigger(trigger);
                                var geofenceTask = geofenceBuilder.Register();
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine(ex.Message);
                            }