后台地理围栏Windows Phone 8.1(WinRT) [英] Geofence in the Background Windows Phone 8.1 (WinRT)

查看:202
本文介绍了后台地理围栏Windows Phone 8.1(WinRT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题



我试图在WP8.1(WinRT)中发生Geofence事件(进入/退出)时触发BackgroundTask。我已经编写了一个示例应用程序来试图使它工作,但似乎无法做到这一点。



到目前为止,这些是我的步骤,已尝试让Geofences在后台运行:


  1. 检查位置功能

  2. 创建+注册地理栅栏

  3. 创建+注册一个BackgroundTask,用于监听 LocationTrigger(LocationTriggerType.Geofence);

  4. 在我的后台任务中,触发一个简单的弹出通知



我对问题所做的事情



我在我的app.manifest中启用了:


  • Toast Capable =>是

  • 功能:位置,互联网(客户端和
    服务器)
  • 声明:BackgroundTasks(位置)。 EntryPoint = BackgroundTask.GeofenceBackgroundTask



我的后台任务位于一个单独的项目,标题为 BackgroundTask 。它是一个WindowsRT组件,包含一个类 GeofenceBackgroundTask




样本项目该项目的代码可以在 [link] 中找到( https://github.com / giangtengl / GeofenceSample ):

如何测试




  1. 在模拟器中运行代码


  2. 将位置设置为:纬度= 01.3369,经度= 103.7364



  1. 单击Register Geofence + BackgroundTasks按钮


  2. 退出应用程序(按主页按钮)


  3. 将当前位置更改为距您之前设置的位置100m处。应该弹出一个通知。



  4. 项目代码:



    检查位置功能



      public static async任务GetLocationCapabilities()
    {
    尝试
    {
    var geolocator = new Geolocator();
    等待geolocator.GetGeopositionAsync();
    var backgroundAccessStatus =等待BackgroundExecutionManager.RequestAccessAsync();
    Debug.WriteLine(后台访问状态+ backgroundAccessStatus);
    }
    catch(UnauthorizedAccessException e)
    {
    Debug.WriteLine(e);

    catch(TaskCanceledException e)
    {
    Debug.WriteLine(e);




    $ h $创建地理栅栏

      public static void CreateGeofence(BasicGeoposition position,double radius,string id =default)
    {
    // Geofence是一个圆形区域以(纬度,经度)为中心,以米为单位的
    //半径。
    var geocircle = new Geocircle(position,radius);

    //设置我们想要处理的事件:在这种情况下,entrace和退出
    //从一个区域内的区域。
    var mask = MonitoredGeofenceStates.Entered | MonitoredGeofenceStates.Exited;

    //指定用户在
    之前必须进入/退出区域的时间//接收通知。
    var dwellTime = TimeSpan.FromSeconds(1);

    //创建Geofence并将其添加到GeofenceMonitor。
    var geofence = new Geofence(id,geocircle,mask,false,dwellTime);

    尝试
    {
    GeofenceMonitor.Current.Geofences.Add(geofence);

    catch(Exception e)
    {
    Debug.WriteLine(e);
    // geofence已经添加到系统
    }

    }



    注册后台任务



      public static async Task RegisterBackgroundTask()
    {
    try
    {
    //创建一个新的后台任务生成器
    var geofenceTaskBuilder = new BackgroundTaskBuilder()
    {
    Name = GeofenceBackgroundTaskName,
    TaskEntryPoint =BackgroundTask.GeofenceBackgroundTask
    };

    //创建一个新的位置触发器
    var trigger = new LocationTrigger(LocationTriggerType.Geofence);

    //将位置触发器与后台任务生成器相关联
    geofenceTaskBuilder.SetTrigger(trigger);

    var geofenceTask = geofenceTaskBuilder.Register();

    //将一个事件处理程序与新的后台任务相关联
    geofenceTask.Completed + =(sender,e)=>
    {
    尝试
    {
    e.CheckResult();

    catch(异常错误)
    {
    Debug.WriteLine(error);
    }
    };

    catch(Exception e)
    {
    //后台任务可能存在

    Debug.WriteLine(e);




    $ h $背景任务代码触发Toast

      namespace BackgroundTask 
    {
    public sealed class GeofenceBackgroundTask:IBackgroundTask
    {
    public void Run(IBackgroundTaskInstance taskInstance )
    {
    var toastTemplate = ToastTemplateType.ToastText02;
    var toastXML = ToastNotificationManager.GetTemplateContent(toastTemplate);
    var textElements = toastXML.GetElementsByTagName(text);
    textElements [0] .AppendChild(toastXML.CreateTextNode(You have left!));

    var toast = new ToastNotification(toastXML);

    ToastNotificationManager.CreateToastNotifier()。Show(toast);




    解决方案

    我发现上面的代码示例以及上面的代码有效。我遇到的问题是Windows Phone 8.1不会自动触发Geofence事件。在触发BackgroundTask之前,您必须等待一段时间<5分钟。



    这也适用于前台的地理围栏。


    Issue

    I'm trying to trigger a BackgroundTask when a Geofence Event (Enter / Exit) occurs in WP8.1 (WinRT). I've written a sample application to try to get it working, but can't seem to be able to do so.

    So far, these are the steps I've taken to try to get Geofences working in the background:

    1. Check for Location Capabilities
    2. Create + Register a Geofence
    3. Create + Register a BackgroundTask that listens for LocationTrigger(LocationTriggerType.Geofence);
    4. In my background task, trigger a simple popup notification

    Things I have done to Troubleshoot

    I have enabled in my app.manifest:

    • Toast Capable => Yes
    • Capabilities: Location, Internet(Client & Server)
    • Declarations: BackgroundTasks (Location). EntryPoint = BackgroundTask.GeofenceBackgroundTask

    My background task is located in a separate project, titled BackgroundTask. It is a WindowsRT Component and contains one class GeofenceBackgroundTask.

    Sample Project

    The code for the project can be found at this [link](https://github.com/kiangtengl/GeofenceSample):

    How To Test

    1. Run the code in the emulator

    2. Set Location to to: Latitude = 01.3369, Longitude = 103.7364

    1. Click the Register Geofence + BackgroundTasks button

    2. Exit the app (press the home button)

    3. Change the current location to anywhere 100m away from the location you set previously. A notification should pop out.

    Project Code:

    Check for Location Capabilities

        public static async Task GetLocationCapabilities()
        {
            try
            {
                var geolocator = new Geolocator();
                await geolocator.GetGeopositionAsync();
                var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
                Debug.WriteLine("background access status" + backgroundAccessStatus);
            }
            catch (UnauthorizedAccessException e)
            {
                Debug.WriteLine(e);
            }
            catch (TaskCanceledException e)
            {
                Debug.WriteLine(e);
            }
        }
    

    Create Geofence

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

    Register Background Task

        public static async Task RegisterBackgroundTask()
        {
            try
            { 
            // Create a new background task builder
            var geofenceTaskBuilder = new BackgroundTaskBuilder()
            {
                Name = GeofenceBackgroundTaskName,
                TaskEntryPoint = "BackgroundTask.GeofenceBackgroundTask"
            };
    
            // Create a new location trigger
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);
    
            // Associate the location trigger with the background task builder
            geofenceTaskBuilder.SetTrigger(trigger);
    
            var geofenceTask = geofenceTaskBuilder.Register();
    
            // Associate an event handler with the new background task
            geofenceTask.Completed += (sender, e) =>
            {
                try
                {
                    e.CheckResult();
                }
                catch(Exception error)
                {
                    Debug.WriteLine(error);
                }
            };
            }
            catch(Exception e)
            {
                // Background task probably exists
    
                Debug.WriteLine(e);
            }
        }
    

    BackgroundTask Code to Trigger Toast

    namespace BackgroundTask
    {
        public sealed class GeofenceBackgroundTask : IBackgroundTask
        {
            public void Run(IBackgroundTaskInstance taskInstance)
            {
                var toastTemplate = ToastTemplateType.ToastText02;
                var toastXML = ToastNotificationManager.GetTemplateContent(toastTemplate);
                var textElements = toastXML.GetElementsByTagName("text");
                textElements[0].AppendChild(toastXML.CreateTextNode("You have left!"));
    
                var toast = new ToastNotification(toastXML);
    
                ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
        }
    }
    

    解决方案

    I've discovered that the above code sample, as well as the above code works. The problem that I was facing was that Windows Phone 8.1 does not automatically trigger a Geofence event. You have to wait a certain amount of time <5 mins before the BackgroundTask is triggered.

    This applies to Geofencing in the foreground as well.

    这篇关于后台地理围栏Windows Phone 8.1(WinRT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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