背景任务地理围栏触发 [英] BackgroundTask geofence triggering

查看:20
本文介绍了背景任务地理围栏触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to showToast when the phone leaves or enter the geofenced location (which is set elsewhere and passed in). The issue is that when the app is in the background the trigger does not occur and I don't see the showToast message. I am changing the location manually using an emulator on my PC.

后台任务> 位置在应用清单下设置.

Background Tasks> Location is set under the app manifest.

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

This is the code I am using to build the Geofence and backgroundtask

//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 中的 Entry point 指向的地方

This code is where I monitor the state of the geofence. This is where the Entry point in the appxmanifest is pointing

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

}

推荐答案

看了你的代码,觉得你的代码是正确的.

After looking at your code, it seems that your code is correct.

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

In order to fire the Geofence Backgroundtask to show the toast information, please make sure the following things:

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

1) Please make sure that you have done all the necessary configuration in the Package.appxmanifest for registering the BackgroundTask, for example you have set the correct EntryPoint and added the "Location" capabilities.

有关详细信息,您可以尝试将您的 Package.appxmanifest 与官方示例 Geolocation 的 Package.appxmanifest.另请检查:创建并注册一个后台任务在应用程序清单中声明后台任务.

For the detailed information, you can try to compare your Package.appxmanifest with the official sample Geolocation’s Package.appxmanifest. Please also check: Create and register a background task and Declare background tasks in the application manifest.

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

2) Please make sure that you know how to set the location in the Emulator manually for simulating the phone leave or enter the geofenced location. For more information about how to set location in the emulator, please check the following article: https://msdn.microsoft.com/library/windows/apps/dn629629.aspx#location_and_driving .

3) 请确保您在模拟器中的第二个位置与您在第一次定义的地理围栏相差不远,因为模拟器的行为类似于真实设备,并且设备不会突然从纽约搬到西雅图.或者 BackgroundTask 不会立即被触发.

3) Please make sure that your second position in your emulator is not really far away from the geofences that you have defined in the first time, because the emulator behaves like a real device, and the device doesn’t expect to suddenly move from New York to Seattle. Or the BackgroundTask will not be fire immediately.

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

4) Background tasks for geofencing cannot launch more frequently than every 2 minutes. If you test geofences in the background, the emulator is capable of automatically starting background tasks. But for the next subsequent background tasks, you need to wait for more than 2 minutes.

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

Besides, I will recommend you refer to the following article about how to use the Windows Phone Emulator for testing apps with geofencing: https://blogs.windows.com/buildingapps/2014/05/28/using-the-windows-phone-emulator-for-testing-apps-with-geofencing/ .

谢谢.

这篇关于背景任务地理围栏触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆