后台任务地理围栏触发

BackgroundTask geofence triggering

我正在尝试在 phone 离开或进入地理围栏位置(在别处设置并传入)时显示 Toast。问题是当应用程序在后台时,触发器不会发生,我也看不到 showToast 消息。我正在使用 PC 上的模拟器手动更改位置。

后台任务> 位置设置在应用程序清单下。

这是我用来构建地理围栏和后台任务的代码

//Creates Geofence and names it "PetsnikkerVacationFence"
public static async Task SetupGeofence(double lat, double lon)
    {
        await RegisterBackgroundTasks();

        if (IsTaskRegistered())
        {

            BasicGeoposition position = new BasicGeoposition();
            position.Latitude = lat;
            position.Longitude = lon;

            double radius = 8046.72; //5 miles in meters
            Geocircle geocircle = new Geocircle(position, radius);
            MonitoredGeofenceStates monitoredStates = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;

            Geofence geofence = new Geofence("PetsnikkerVacationFence", geocircle, monitoredStates, false);

            GeofenceMonitor monitor = GeofenceMonitor.Current;

            var existingFence = monitor.Geofences.SingleOrDefault(f => f.Id == "PetsnikkerVacationFence");

            if (existingFence != null)
                monitor.Geofences.Remove(existingFence);

            monitor.Geofences.Add(geofence);

        }




    }

    //Registers the background task with a LocationTrigger
    static async Task RegisterBackgroundTasks()
    {
        var access = await BackgroundExecutionManager.RequestAccessAsync();


        if (access == BackgroundAccessStatus.Denied)
        {

        }
        else
        {
            var taskBuilder = new BackgroundTaskBuilder();
            taskBuilder.Name = "PetsnikkerVacationFence";

            taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
            taskBuilder.SetTrigger(new LocationTrigger(LocationTriggerType.Geofence));

            taskBuilder.TaskEntryPoint = typeof(Petsnikker.Windows.Background.GeofenceTask).FullName;

            var registration = taskBuilder.Register();

            registration.Completed += (sender, e) =>
            {
                try
                {
                    e.CheckResult();
                }
                catch (Exception error)
                {
                    Debug.WriteLine(error);
                }
            };



        }

    }

    static bool IsTaskRegistered()
    {
        var Registered = false;
        var entry = BackgroundTaskRegistration.AllTasks.FirstOrDefault(keyval => keyval.Value.Name == "PetsnikkerVacationFence");
        if (entry.Value != null)
            Registered = true;
        return Registered;
    }
}
}

这段代码是我监控地理围栏状态的地方。 这是 appxmanifest 中的入口点指向的地方

public sealed class GeofenceTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {

        var monitor = GeofenceMonitor.Current;
        if (monitor.Geofences.Any())
        {
            var reports = monitor.ReadReports();
            foreach (var report in reports)
            {


                switch (report.NewState)
                {
                    case GeofenceState.Entered:
                    {

                            ShowToast("Approaching Home",":-)");
                            break;
                    }
                    case GeofenceState.Exited:
                    {
                            ShowToast("Leaving Home", ":-)");
                            break;


                    }


                }
            }
        }


        //deferral.Complete();
    }

    private static void ShowToast(string firstLine, string secondLine)
    {
        var toastXmlContent =
          ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

        var txtNodes = toastXmlContent.GetElementsByTagName("text");
        txtNodes[0].AppendChild(toastXmlContent.CreateTextNode(firstLine));
        txtNodes[1].AppendChild(toastXmlContent.CreateTextNode(secondLine));

        var toast = new ToastNotification(toastXmlContent);
        var toastNotifier = ToastNotificationManager.CreateToastNotifier();
        toastNotifier.Show(toast);

        Debug.WriteLine("Toast: {0} {1}", firstLine, secondLine);
    }

}

看了你的代码,看来你的代码是正确的。

为了触发 Geofence Backgroundtask 以显示 toast 信息,请确保以下事项:

1) 请确保您已在 Package.appxmanifest 中完成所有必要的配置以注册 BackgroundTask,例如您已设置正确的 EntryPoint 并添加“位置”功能

详细信息,您可以尝试将您的Package.appxmanifest与官方样本Geolocation的Package.appxmanifest进行比较。 另请检查:Create and register a background task and Declare background tasks in the application manifest.

2) 请确保您知道如何在模拟器中手动设置位置以模拟 phone 离开或进入地理围栏位置。有关如何在模拟器中设置位置的更多信息,请查看以下文章: https://msdn.microsoft.com/library/windows/apps/dn629629.aspx#location_and_driving .

3) 请确保您在模拟器中的第二个位置与您第一次定义的地理围栏的距离不是很远,因为模拟器的行为就像真正的设备,并且该设备不会突然从纽约搬到西雅图。或者 BackgroundTask 不会立即启动。

4) 地理围栏后台任务的启动频率不得高于每 2 分钟一次。如果您在后台测试地理围栏,模拟器能够自动启动后台任务。但是接下来的后续后台任务,需要等待2分钟以上

此外,我建议您参考以下文章,了解如何使用 Windows Phone 模拟器来测试带有地理围栏的应用程序: https://blogs.windows.com/buildingapps/2014/05/28/using-the-windows-phone-emulator-for-testing-apps-with-geofencing/.

谢谢。