private async void StartInBackground_Click(object s, RoutedEventArgs e)
        {
            var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
            var geofenceTaskBuilder = new BackgroundTaskBuilder
            {
                Name = "GeofenceBackgroundTask",
                TaskEntryPoint = "BackgroundTask.GeofenceBackgroundTask"
            };

            var trigger = new LocationTrigger(LocationTriggerType.Geofence);
            geofenceTaskBuilder.SetTrigger(trigger);
            var geofenceTask = geofenceTaskBuilder.Register();
            geofenceTask.Completed += (sender, args) =>
            {
                var geoReports = GeofenceMonitor.Current.ReadReports();
                foreach (var geofenceStateChangeReport in geoReports)
                {
                    var id = geofenceStateChangeReport.Geofence.Id;
                    var newState = geofenceStateChangeReport.NewState.ToString();
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        new MessageDialog(newState + " : " + id)
                        .ShowAsync());
                }
            };
        }
        /// <summary>
        /// This is the click handler for the 'Register' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                // Regardless of the answer, register the background task. If the user later adds this application
                // to the lock screen, the background task will be ready to run.
                // Create a new background task builder
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name           = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;

                // Create a new location trigger
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                // Associate the locationi trigger with the background task builder
                geofenceTaskBuilder.SetTrigger(trigger);

                // If it is important that there is user presence and/or
                // internet connection when OnCompleted is called
                // the following could be called before calling Register()
                // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
                // geofenceTaskBuilder.AddCondition(condition);

                // Register the background task
                _geofenceTask = geofenceTaskBuilder.Register();

                // Associate an event handler with the new background task
                _geofenceTask.Completed += OnCompleted;

                UpdateButtonStates(/*registered:*/ true);

                switch (backgroundAccessStatus)
                {
                case BackgroundAccessStatus.AlwaysAllowed:
                case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:
                    // BackgroundTask is allowed
                    _rootPage.NotifyUser("Geofence background task registered.", NotifyType.StatusMessage);

                    // Need to request access to location
                    // This must be done with the background task registeration
                    // because the background task cannot display UI.
                    RequestLocationAccess();
                    break;

                default:
                    _rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage);
                    break;
                }
            }
            catch (Exception ex)
            {
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                UpdateButtonStates(/*registered:*/ false);
            }
        }
Пример #3
0
        /// <summary>
        /// Registers a Background Task that is used for reacting on Geofence-Reports.
        /// </summary>
        /// <returns>A Background Task for reacting on Geofence-Reports.</returns>
        private async Task RegisterGeofenceTask()
        {
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            var geofenceTaskBuilder = new BackgroundTaskBuilder
            {
                Name           = "ShoppinglistGeofenceTask",
                TaskEntryPoint = "GeofenceTask.BackgroundGeofenceTask"
            };

            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            geofenceTaskBuilder.SetTrigger(trigger);

            var geofenceTask = geofenceTaskBuilder.Register();

            switch (backgroundAccessStatus)
            {
            case BackgroundAccessStatus.Unspecified:
            case BackgroundAccessStatus.Denied:
                await dialogService.ShowMessage(
                    ResourceLoader.GetForCurrentView().GetString("RegisterBackgroundTaskError"),
                    ResourceLoader.GetForCurrentView().GetString("AccessDeniedTitle"));

                break;
            }
        }
Пример #4
0
        public async Task <IBackgroundTaskRegistration> RegisterBackgroundTask()
        {
            if (BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == BackgroundTaskName))
            {
                return(null);
            }

            switch (await BackgroundExecutionManager.RequestAccessAsync())
            {
            case BackgroundAccessStatus.AlwaysAllowed:
            case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:
                RequestLocationAccess();
                break;

            default:
                throw new Exception("Background task disabled");
            }

            var geofenceTaskBuilder = new BackgroundTaskBuilder()
            {
                Name           = BackgroundTaskName,
                TaskEntryPoint = BackgroundTaskEntryPoint
            };

            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            geofenceTaskBuilder.SetTrigger(trigger);

            backgroundTask = geofenceTaskBuilder.Register();
            return(backgroundTask);
        }
Пример #5
0
        private async Task RegisterBackgroundTask()
        {
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            var geofenceTaskBuilder = new BackgroundTaskBuilder
            {
                Name           = "My Home Geofence",
                TaskEntryPoint = "GeofenceTask.BackgroundGeofenceTask"
            };

            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            geofenceTaskBuilder.SetTrigger(trigger);

            var geofenceTask = geofenceTaskBuilder.Register();

            geofenceTask.Completed += GeofenceTask_Completed;

            switch (backgroundAccessStatus)
            {
            case BackgroundAccessStatus.Unspecified:
            case BackgroundAccessStatus.Denied:
                ShowMessage("This application is denied of the background task ");
                break;
            }
        }
Пример #6
0
        /// <summary>
        /// This is the click handler for the 'Register' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
        {
            // Register the background task without checking whether the user has enabled background execution.
            // If it's disabled, and then the user later enables background execution, the background task will be ready to run.
            // Create a new background task builder
            BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

            geofenceTaskBuilder.Name           = BackgroundTaskName;
            geofenceTaskBuilder.TaskEntryPoint = BackgroundTaskEntryPoint;

            // Create a new location trigger
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            // Associate the location trigger with the background task builder
            geofenceTaskBuilder.SetTrigger(trigger);

            // If it is important that there is user presence and/or
            // internet connection when OnCompleted is called
            // the following could be called before calling Register()
            // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
            // geofenceTaskBuilder.AddCondition(condition);

            // Register the background task
            _geofenceTask = geofenceTaskBuilder.Register();

            // Associate an event handler with the new background task
            _geofenceTask.Completed += OnCompleted;

            UpdateButtonStates();
            MainPage.CheckBackgroundAndRequestLocationAccess();
        }
Пример #7
0
        async private Task RegisterBackgroundTask()
        {
            // Get permission for a background task from the user. If the user has already answered once,
            // this does nothing and the user must manually update their preference via PC Settings.
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            // Regardless of the answer, register the background task. Note that the user can use
            // the Settings app to prevent your app from running background tasks.
            // Create a new background task builder
            BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

            geofenceTaskBuilder.Name = "Geofence";
            geofenceTaskBuilder.TaskEntryPoint = "Perimetr.BackgroundTasks.GeofenceBackgroundTask";

            // Create a new location trigger
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            // Associate the locationi trigger with the background task builder
            geofenceTaskBuilder.SetTrigger(trigger);

            // If it is important that there is user presence and/or
            // internet connection when OnCompleted is called
            // the following could be called before calling Register()
            // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
            // geofenceTaskBuilder.AddCondition(condition);

            // Register the background task
            var geofenceTask = geofenceTaskBuilder.Register();

            // Associate an event handler with the new background task
            geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

            switch (backgroundAccessStatus)
            {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    break;

            }

            var accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
                case GeolocationAccessStatus.Allowed:
                    geofences = GeofenceMonitor.Current.Geofences;

                    // register for state change events
                    GeofenceMonitor.Current.GeofenceStateChanged += stateChange;
                    GeofenceMonitor.Current.StatusChanged += statusChanged;
                    break;

                case GeolocationAccessStatus.Denied:
                    break;

                case GeolocationAccessStatus.Unspecified:
                    break;
            }
        }
Пример #8
0
    LocationTrigger FindLocationTrigger(int x, int y, bool playerSide)
    {
        LocationTrigger ret = null;

        ret = _locationTriggers.Find(t => (t._locationX == x) && (t._locationY == y) && (t._playerSide == playerSide));

        return(ret);
    }
Пример #9
0
        //注册后台任务
        private async void RegisterTask()
        {
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);
            var task    = await App.RegisterBackgroundTask(typeof(BackgroundCore), "LocationTask", trigger, null);

            task.Progress  += Task_Progress;
            task.Completed += Task_Completed;
        }
Пример #10
0
        async private void registerBackgroundTask()
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                // Regardless of the answer, register the background task. If the user later adds this application
                // to the lock screen, the background task will be ready to run.
                // Create a new background task builder
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name           = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = typeof(GeofenceBackgroundTask).FullName;

                // Create a new location trigger
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                // Associate the locationi trigger with the background task builder
                geofenceTaskBuilder.SetTrigger(trigger);

                // If it is important that there is user presence and/or
                // internet connection when OnCompleted is called
                // the following could be called before calling Register()
                //SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
                //geofenceTaskBuilder.AddCondition(condition);

                // Register the background task
                _geofenceTask = geofenceTaskBuilder.Register();

                // Associate an event handler with the new background task
                _geofenceTask.Completed += OnCompleted;

                switch (backgroundAccessStatus)
                {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    System.Diagnostics.Debug.WriteLine("Not able to run in background. Application must be added to the lock screen.");
                    break;

                default:
                    // BckgroundTask is allowed
                    System.Diagnostics.Debug.WriteLine("Geofence background task registered.");

                    // Need to request access to location
                    // This must be done with the background task registeration
                    // because the background task cannot display UI.
                    requestLocationAccess();
                    break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Пример #11
0
 public void CheckTriggerEvent(int x, int y, int type)
 {
     if (_triggerEvent == null)
     {
         LocationTrigger temp = FindLocationTrigger(x, y, type == 1 ? true : false);
         if (temp != null)
         {
             temp.TriggerCheck();
         }
     }
 }
Пример #12
0
        /// <summary>
        /// Cannot avoid this method being blocking on the UI thread, because creating the background task requires it
        /// (otherwise creating the LocationTrigger gives a COM exception)
        /// </summary>
        public async Task On(string backgroundTaskEntryPoint)
        {
            if (string.IsNullOrWhiteSpace(backgroundTaskEntryPoint)) throw new ArgumentNullException(nameof(backgroundTaskEntryPoint));

            await _permissionRepository.RequestRequired();

            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
                () => 
                {
                    var trigger = new LocationTrigger(LocationTriggerType.Geofence);
                    var condition = new SystemCondition(SystemConditionType.InternetAvailable);

                    _backgroundTaskRegistrar.Register(backgroundTaskEntryPoint,
                        BackgroundTaskName, trigger, condition);
                });

            _applicationRepository.UpdateIsEnabled(isEnabled: true);
        }
        private async static Task <bool> RegisterInternal()
        {
            if (!IsTaskRegistered())
            {
                await BackgroundExecutionManager.RequestAccessAsync();

                var builder = new BackgroundTaskBuilder()
                {
                    Name           = TaskName,
                    TaskEntryPoint = typeof(BackgroundTask).FullName
                };
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);
                builder.SetTrigger(trigger);
                builder.Register();
                return(true);
            }
            return(false);
        }
Пример #14
0
        async private void RegisterGeoFence()
        {
            try
            {
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name           = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                geofenceTaskBuilder.SetTrigger(trigger);
                _geofenceTask = geofenceTaskBuilder.Register();
            }
            catch
            {
            }
        }
Пример #15
0
        public static async void Register()
        {

            // Get permission for a background task from the user. If the user has already answered once,
            // this does nothing and the user must manually update their preference via PC Settings.
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            // Regardless of the answer, register the background task. If the user later adds this application
            // to the lock screen, the background task will be ready to run.
            // Create a new background task builder
            BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

            geofenceTaskBuilder.Name = TaskName;
            geofenceTaskBuilder.TaskEntryPoint = typeof(GeofenceTask).ToString();

            // Create a new location trigger
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            // Associate the locationi trigger with the background task builder
            geofenceTaskBuilder.SetTrigger(trigger);

            // If it is important that there is user presence and/or
            // internet connection when OnCompleted is called
            // the following could be called before calling Register()
            // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
            // geofenceTaskBuilder.AddCondition(condition);

            // Register the background task
            var geofenceTask = geofenceTaskBuilder.Register();

            Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, "Registered Geofence Background Task"));

            switch (backgroundAccessStatus)
            {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    //rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage);
                    break;
            }


        }
Пример #16
0
        /// <summary>
        /// Cannot avoid this method being blocking on the UI thread, because creating the background task requires it
        /// (otherwise creating the LocationTrigger gives a COM exception)
        /// </summary>
        public async Task On(string backgroundTaskEntryPoint)
        {
            if (string.IsNullOrWhiteSpace(backgroundTaskEntryPoint))
            {
                throw new ArgumentNullException(nameof(backgroundTaskEntryPoint));
            }

            await _permissionRepository.RequestRequired();

            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                          () =>
            {
                var trigger   = new LocationTrigger(LocationTriggerType.Geofence);
                var condition = new SystemCondition(SystemConditionType.InternetAvailable);

                _backgroundTaskRegistrar.Register(backgroundTaskEntryPoint,
                                                  BackgroundTaskName, trigger, condition);
            });

            _applicationRepository.UpdateIsEnabled(isEnabled: true);
        }
Пример #17
0
        private async void GRegister_Click(object sender, RoutedEventArgs e)
        {
            // Get permission for a background task from the user. If the user has already answered once,
            //this does nothing and the user must manually update their preference via PC Settings.
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            // Regardless of the answer, register the background task. If the user later adds this application
            // to the lock screen, the background task will be ready to run.
            // Create a new background task builder
            BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

            geofenceTaskBuilder.Name           = SaferConfiguration.GetTaskName();
            geofenceTaskBuilder.TaskEntryPoint = SaferConfiguration.GetTaskEntryPoint();

            // Create a new location trigger
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            // Associate the locationi trigger with the background task builder
            geofenceTaskBuilder.SetTrigger(trigger);

            // If it is important that there is user presence and/or
            // internet connection when OnCompleted is called
            // the following could be called before calling Register()
            // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
            // geofenceTaskBuilder.AddCondition(condition);

            // Register the background task
            saferAccelerometerRegistrationGeofence = geofenceTaskBuilder.Register();

            // Associate an event handler with the new background task
            saferAccelerometerRegistrationGeofence.Completed += new BackgroundTaskCompletedEventHandler(OnBackgroundTaskCompleted);

            switch (backgroundAccessStatus)
            {
            case BackgroundAccessStatus.Unspecified:
            case BackgroundAccessStatus.Denied:
                Error = "This application must be added to the lock screen before the background task will run.";
                break;
            }
        }
Пример #18
0
        public static async void Register()
        {
            // Get permission for a background task from the user. If the user has already answered once,
            // this does nothing and the user must manually update their preference via PC Settings.
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            // Regardless of the answer, register the background task. If the user later adds this application
            // to the lock screen, the background task will be ready to run.
            // Create a new background task builder
            BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

            geofenceTaskBuilder.Name           = TaskName;
            geofenceTaskBuilder.TaskEntryPoint = typeof(GeofenceTask).ToString();

            // Create a new location trigger
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            // Associate the locationi trigger with the background task builder
            geofenceTaskBuilder.SetTrigger(trigger);

            // If it is important that there is user presence and/or
            // internet connection when OnCompleted is called
            // the following could be called before calling Register()
            // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
            // geofenceTaskBuilder.AddCondition(condition);

            // Register the background task
            var geofenceTask = geofenceTaskBuilder.Register();

            Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, "Registered Geofence Background Task"));

            switch (backgroundAccessStatus)
            {
            case BackgroundAccessStatus.Unspecified:
            case BackgroundAccessStatus.Denied:
                //rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage);
                break;
            }
        }
Пример #19
0
        async private void RegisterGeofenceBackgroundTask()
        {
            // Request access for background task. No prompt is shown to the user in Windows Phone.
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            // Create a new background task builder
            BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

            geofenceTaskBuilder.Name           = backgroundTaskName;
            geofenceTaskBuilder.TaskEntryPoint = backgroundTaskEntryPoint;

            // Create a new location trigger
            var trigger = new LocationTrigger(LocationTriggerType.Geofence);

            // Associate the location trigger with the background task builder
            geofenceTaskBuilder.SetTrigger(trigger);

            // Register the background task
            geofenceTask = geofenceTaskBuilder.Register();

            // Optional Associate an event handler with the new background task
            // geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnGeofenceBackgroundTaskCompleted);

            switch (backgroundAccessStatus)
            {
            case BackgroundAccessStatus.Unspecified:
            case BackgroundAccessStatus.Denied:
                Debug.WriteLine("This application must be added to the lock screen before the background task will run.");
                break;

            default:
                // The following would need to be done in Windows, but not needed in Windows Phone
                // Ensure we have presented the location consent prompt (by asynchronously getting the current
                // position). This must be done here because the background task cannot display UI.
                //GetGeopositionAsync();
                break;
            }
        }
Пример #20
0
        private async Task RegisterBackgroundTaskAsync(string taskName, string taskEntryPoint)
        {
            BackgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            if (IsTaskRegistered)
            {
                SubscribeBackgroundTaskEvents(RegisteredTask);
                return;
            }

            var backgroundTaskBuilder = new BackgroundTaskBuilder()
            {
                Name           = taskName,
                TaskEntryPoint = taskEntryPoint,
            };

            var locationTrigger = new LocationTrigger(LocationTriggerType.Geofence);

            backgroundTaskBuilder.SetTrigger(locationTrigger);

            backgroundTaskBuilder.Register();

            SubscribeBackgroundTaskEvents(RegisteredTask);
        }
Пример #21
0
        async private void RegisterGeoFence()
        {
            try
            {
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
                
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);
                
                geofenceTaskBuilder.SetTrigger(trigger);
                _geofenceTask = geofenceTaskBuilder.Register();
                
            }
            catch
            {
            }
        }
        /// <summary>
        /// This is the click handler for the 'Register' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                // Regardless of the answer, register the background task. If the user later adds this application
                // to the lock screen, the background task will be ready to run.
                // Create a new background task builder
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name           = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;

                // Create a new location trigger
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                // Associate the locationi trigger with the background task builder
                geofenceTaskBuilder.SetTrigger(trigger);

                // If it is important that there is user presence and/or
                // internet connection when OnCompleted is called
                // the following could be called before calling Register()
                // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
                // geofenceTaskBuilder.AddCondition(condition);

                // Register the background task
                geofenceTask = geofenceTaskBuilder.Register();

                // Associate an event handler with the new background task
                geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

                UpdateButtonStates(/*registered:*/ true);

                switch (backgroundAccessStatus)
                {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
#if WINDOWS_APP
                    rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage);
#else
                    rootPage.NotifyUser("Not able to run in background.", NotifyType.ErrorMessage);
#endif
                    break;

                default:
                    // Ensure we have presented the location consent prompt (by asynchronously getting the current
                    // position). This must be done here because the background task cannot display UI.
                    GetGeopositionAsync();
                    break;
                }
            }
            catch (Exception ex)
            {
#if WINDOWS_APP
                // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) == 0x80070032
                const int RequestNotSupportedHResult = unchecked ((int)0x80070032);

                if (ex.HResult == RequestNotSupportedHResult)
                {
                    rootPage.NotifyUser("Location Simulator not supported.  Could not get permission to add application to the lock screen, this application must be added to the lock screen before the background task will run.", NotifyType.StatusMessage);
                }
                else
#endif
                {
                    rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                }

                UpdateButtonStates(/*registered:*/ false);
            }
        }
Пример #23
0
        private async Task RegisterBackgroundTask()
        {
            BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

            var geofenceTaskBuilder = new BackgroundTaskBuilder
            {
                Name = "My Home Geofence",
                TaskEntryPoint = "GeofenceTask.BackgroundGeofenceTask"
            };

            var trigger = new LocationTrigger(LocationTriggerType.Geofence);
            geofenceTaskBuilder.SetTrigger(trigger);

            var geofenceTask = geofenceTaskBuilder.Register();
            geofenceTask.Completed += GeofenceTask_Completed;

            switch (backgroundAccessStatus)
            {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    ShowMessage("This application is denied of the background task ");
                    break;
            }

        }
Пример #24
0
        private async void Register()
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                switch (backgroundAccessStatus)
                {
                case BackgroundAccessStatus.Unspecified:
                case BackgroundAccessStatus.Denied:
                    Debug.WriteLine("Not able to run in background. Application must be added to the lock screen.");
                    this.IsTaskRegistered = false;
                    break;

                default:
                    // BckgroundTask is allowed
                    Debug.WriteLine("Geofence background task registered.");

                    // Need to request access to location
                    // This must be done with the background task registration
                    // because the background task cannot display UI.
                    bool locationAccess = await RequestLocationAccess();

                    if (locationAccess)
                    {
                        BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                        geofenceTaskBuilder.Name           = nameof(GeofenceBackgroundTask);
                        geofenceTaskBuilder.TaskEntryPoint = typeof(GeofenceBackgroundTask).ToString();

                        // Create a new location trigger
                        var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                        // Associate the locationi trigger with the background task builder
                        geofenceTaskBuilder.SetTrigger(trigger);
                        geofenceTaskBuilder.AddCondition(new SystemCondition(SystemConditionType.BackgroundWorkCostNotHigh));

                        // Register the background task
                        _geofenceTask = geofenceTaskBuilder.Register();

                        this.IsTaskRegistered = true;
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            if (this.IsTaskRegistered)
            {
                var successDialog = new MessageDialog("Task registered");
                await successDialog.ShowAsync();
            }
            else
            {
                var errorDialog = new MessageDialog("Error registering task");
                await errorDialog.ShowAsync();
            }
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            IHttpFilter filter = new AuthFilter(new HttpBaseProtocolFilter());

            _httpClient = new HttpClient(filter);

            _isConnectedToInternet = (null != NetworkInformation.GetInternetConnectionProfile());
            NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged;

            Logger.Initialize(LoggerTextBox, LoggerScrollViewer);
            await LogBackgroundEventsAsync();

            ShowStatus("Waiting for location...");

            try
            {
                _geolocator  = new Geolocator();
                _geoposition = await _geolocator.GetGeopositionAsync();

                ClearStatus();

                var position = _geoposition.Coordinate.Point.Position;
                Logger.Trace(TraceLevel.Info, String.Format("Current Location: {0}, Accuracy: {1} meters",
                                                            Logger.FormatLatLong(position.Latitude, position.Longitude),
                                                            _geoposition.Coordinate.Accuracy));

                // Initialize map
                var mapCenter = new Bing.Maps.Location(position.Latitude, position.Longitude);
                Map.SetView(mapCenter, Constants.DefaultMapZoomLevel);

                _currentLocationPushpin = new Bing.Maps.Pushpin();
                CurrentPositionMapLayer.Children.Add(_currentLocationPushpin);
                Bing.Maps.MapLayer.SetPosition(_currentLocationPushpin, mapCenter);

                // Register for position changed events
                _geolocator.PositionChanged += OnGeopositionChanged;

                // Loop through all background tasks to see if our background task is already registered
                foreach (var cur in BackgroundTaskRegistration.AllTasks)
                {
                    if (cur.Value.Name == _backgroundTaskName)
                    {
                        _geofenceTask = cur.Value;
                        break;
                    }
                }

                if (_geofenceTask != null)
                {
                    // Associate an event handler with the existing background task
                    _geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
                }
                else
                {
                    // Get permission for a background task from the user. If the user has already answered once,
                    // this does nothing and the user must manually update their preference via PC Settings.
                    var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                    switch (backgroundAccessStatus)
                    {
                    case BackgroundAccessStatus.Unspecified:
                    case BackgroundAccessStatus.Denied:
                        ShowStatus("This application must be added to the lock screen in order to do automatic checkins.");
                        break;

                    default:
                        break;
                    }

                    // Register the background task.
                    var geofenceTaskBuilder = new BackgroundTaskBuilder();

                    geofenceTaskBuilder.Name           = _backgroundTaskName;
                    geofenceTaskBuilder.TaskEntryPoint = _backgroundTaskEntryPoint;

                    // Create a new location trigger
                    var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                    // Associate the location trigger with the background task builder
                    geofenceTaskBuilder.SetTrigger(trigger);

                    // Ensure there is an internet connection before the background task is launched.
                    var condition = new SystemCondition(SystemConditionType.InternetAvailable);
                    geofenceTaskBuilder.AddCondition(condition);

                    // Register the background task
                    _geofenceTask = geofenceTaskBuilder.Register();

                    // Associate an event handler with the new background task
                    _geofenceTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

                    Logger.Trace(TraceLevel.Debug, "Background registration succeeded");
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                ShowStatus("Location access denied, please go to Settings -> Permissions to grant this app access to your location.");
                Logger.Trace(TraceLevel.Warn, "Access denied when getting location");
            }
            catch (TaskCanceledException)
            {
                ShowStatus("Location acquisition was canceled. Close and re-launch this app if you would like to try again.");
                Logger.Trace(TraceLevel.Warn, "Canceled getting location");
            }
            catch (Exception ex)
            {
                Logger.Trace(TraceLevel.Error, "Could not acquire location or register background trigger: " + Logger.FormatException(ex));
            }

            Settings.Changed += OnSettingsChanged;
            Logger.Trace(TraceLevel.Info, "Foursquare query limit setting: " + Settings.QueryLimit + " places");
            Logger.Trace(TraceLevel.Info, "Geofence creation radius setting: " + Settings.GeofenceRadiusMeters + " meters");
        }
        /// <summary>
        /// This is the click handler for the 'Register' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get permission for a background task from the user. If the user has already answered once,
                // this does nothing and the user must manually update their preference via PC Settings.
                BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

                // Regardless of the answer, register the background task. If the user later adds this application
                // to the lock screen, the background task will be ready to run.
                // Create a new background task builder
                BackgroundTaskBuilder geofenceTaskBuilder = new BackgroundTaskBuilder();

                geofenceTaskBuilder.Name = SampleBackgroundTaskName;
                geofenceTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;

                // Create a new location trigger
                var trigger = new LocationTrigger(LocationTriggerType.Geofence);

                // Associate the locationi trigger with the background task builder
                geofenceTaskBuilder.SetTrigger(trigger);

                // If it is important that there is user presence and/or
                // internet connection when OnCompleted is called
                // the following could be called before calling Register()
                // SystemCondition condition = new SystemCondition(SystemConditionType.UserPresent | SystemConditionType.InternetAvailable);
                // geofenceTaskBuilder.AddCondition(condition);

                // Register the background task
                _geofenceTask = geofenceTaskBuilder.Register();

                // Associate an event handler with the new background task
                _geofenceTask.Completed += OnCompleted;

                UpdateButtonStates(/*registered:*/ true);

                switch (backgroundAccessStatus)
                {

                    case BackgroundAccessStatus.Unspecified:
                    case BackgroundAccessStatus.Denied:
                        _rootPage.NotifyUser("Not able to run in background. Application must be added to the lock screen.",
                                              NotifyType.ErrorMessage);
                        break;

                    default:
                        // BckgroundTask is allowed
                        _rootPage.NotifyUser("Geofence background task registered.", NotifyType.StatusMessage);

                        // Need to request access to location
                        // This must be done with the background task registeration
                        // because the background task cannot display UI.
                        RequestLocationAccess();
                        break;
                }
            }
            catch (Exception ex)
            {
                _rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
                UpdateButtonStates(/*registered:*/ false);
            }
        }