Inheritance: IBackgroundTaskRegistration
        async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

            var promise = await BackgroundExecutionManager.RequestAccessAsync();

            if (promise == BackgroundAccessStatus.Denied)
            {
                MessageDialog warningDialog = new MessageDialog("Background execution is disabled. Please re-enable in the Battery Saver app to allow this app to function", "Background GPS");
                await warningDialog.ShowAsync();
            }
            else
            {
                var defaultSensor = Windows.Devices.Sensors.Accelerometer.GetDefault();
                if (defaultSensor != null)
                {
                    var deviceUseTrigger = new DeviceUseTrigger();

                    deviceUseTask = RegisterBackgroundTask("BackgroundGps.Engine.BackgroundGpsTask", "GpsTask", deviceUseTrigger, null);

                    try
                    {
                        DeviceTriggerResult r = await deviceUseTrigger.RequestAsync(defaultSensor.DeviceId);

                        System.Diagnostics.Debug.WriteLine(r); //Allowed 
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                    }
                }
            }
        }
        public static IAsyncOperation<BackgroundTaskRegistration> RegisterTaskAsync()
        {
            return AsyncInfo.Run(async (cancellationToken) =>
            {
                if (IsTaskRegistered())
                    return _current;

                await BackgroundExecutionManager.RequestAccessAsync();


                //http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.background.timetrigger.aspx
                IBackgroundTrigger trigger = new TimeTrigger(6*60, false); //6 hours

                // Builds the background task.
                BackgroundTaskBuilder builder = new BackgroundTaskBuilder();

                builder.Name = FriendlyName;
                builder.TaskEntryPoint = typeof(BackgroundDemoTask).FullName;
                builder.SetTrigger(trigger);

                SystemCondition condition = new SystemCondition(SystemConditionType.InternetAvailable);
                builder.AddCondition(condition);

                // Registers the background task, and get back a BackgroundTaskRegistration object
                // representing the registered task.
                _current = builder.Register();
                return _current;
            });
        }
 void Task_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     if (deferral != null)
     {
         deferral.Complete();
     }
 }
示例#4
0
        public static void Register()
        {
             
            foreach (var iter in BackgroundTaskRegistration.AllTasks)
            {
                IBackgroundTaskRegistration mytask = iter.Value;
                if (mytask.Name == "ExampleBackgroundTask")
                {

                    mytask.Unregister(true);
                    break;
                }
            }

           
            var builder = new BackgroundTaskBuilder();
            PushNotificationTrigger trigger = new PushNotificationTrigger();
            builder.SetTrigger(trigger);
            builder.Name = "ExampleBackgroundTask";
            builder.TaskEntryPoint = "Usergrid.Notifications.ExampleBackgroundTask";

            ExampleBackgroundTask.task = builder.Register();
            task.Progress += task_Progress;

            task.Completed += task_Completed;

        }
 public static void UnregisterTask()
 {
     if (IsTaskRegistered())
     {
         _current.Unregister(true);
         _current = null;
     }
 }
        private async void OnProgress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args)
        {
            // Serialize UI update to the the main UI thread.
            await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ShowErrorDialog(CommonData.LastMessage,"Got message");

            });
        }
 void OnProgress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args)
 {
     Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
         () =>
         {
             if (this.mediaElement.Visibility == Visibility.Collapsed)
             {
                 this.mediaElement.Visibility = Visibility.Visible;
                 this.mediaElement.Play();
             }
             this.txtTaskRunning.Text = "Running";
             this.progressBar.Value = args.Progress;
         });
 }
 public static bool IsTaskRegistered()
 {
     if (_current == null)
     {
         foreach (var cur in BackgroundTaskRegistration.AllTasks)
         {
             if (cur.Value.Name == FriendlyName)
             {
                 // The task is already registered.
                 _current = (BackgroundTaskRegistration)(cur.Value);
             }
         }
     }
     return _current != null;
 }
示例#9
0
        public static async Task<BackgroundTaskRegistration> RegisterLogsUploadTask()
        {
            if (LogsUploadTask != null)
            {
                return LogsUploadTask;
            }

            if (Log.IsDebugEnabled)
                Log.Debug("Registering LogsUpload background task.");

            var accessStatus = await SetUpAccess();
            if (accessStatus == BackgroundAccessStatus.Denied) return null;

            var result = RegisterBackgroundTask(typeof(LogsUploadTask).FullName,
                                                "LinquaLogsUpload",
                                                new TimeTrigger(LogsUploadTaskIntervalMinutes, false),
                                                new SystemCondition(SystemConditionType.InternetAvailable));
            LogsUploadTask = result;

            if (Log.IsDebugEnabled)
                Log.Debug("Background task registered. TaskId: {0}", result.TaskId);

            return result;
        }
示例#10
0
 private static void BgTask_Progress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args)
 {
     LogMessage("BgTask Progress: " + args.Progress, NotifyType.StatusMessage);
 }
示例#11
0
        private void CancelSyncWithDevice()
        {
            if (isSyncing)
            {
                backgroundSyncTaskRegistration.Unregister(true);

                backgroundSyncTaskRegistration = null;

                // We are canceling the task, so we are no longer syncing. If the task is registered but never run,
                // the cancel completion is never called
                isSyncing = false;
            }
        }
 private async void OnTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         rootPage.NotifyUser("Background task completed", NotifyType.StatusMessage);
     });
 }
示例#13
0
 private static void BgTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     LogMessage("BgTask Completed", NotifyType.StatusMessage);
 }
        /// <summary>
        /// Starts the sensor background task.
        /// </summary>
        /// <param name="deviceId">Device Id for the sensor to be used by the task.</param>
        /// <param name="e"></param>
        /// <returns>True if the task is started successfully.</returns>
        private async Task<bool> StartSensorBackgroundTaskAsync(String deviceId)
        {
            bool started = false;

            // Make sure only 1 task is running.
            FindAndCancelExistingBackgroundTask();

            // Register the background task.
            var backgroundTaskBuilder = new BackgroundTaskBuilder()
            {
                Name = SampleConstants.Scenario1_TaskName,
                TaskEntryPoint = SampleConstants.Scenario1_TaskEntryPoint
            };

            backgroundTaskBuilder.SetTrigger(_deviceUseTrigger);
            _deviceUseBackgroundTaskRegistration = backgroundTaskBuilder.Register();

            // Make sure we're notified when the task completes or if there is an update.
            _deviceUseBackgroundTaskRegistration.Completed += new BackgroundTaskCompletedEventHandler(OnBackgroundTaskCompleted);

            try
            {
                // Request a DeviceUse task to use the accelerometer.
                DeviceTriggerResult deviceTriggerResult = await _deviceUseTrigger.RequestAsync(deviceId);

                switch (deviceTriggerResult)
                {
                    case DeviceTriggerResult.Allowed:
                        rootPage.NotifyUser("Background task started", NotifyType.StatusMessage);
                        started = true;
                        break;

                    case DeviceTriggerResult.LowBattery:
                        rootPage.NotifyUser("Insufficient battery to run the background task", NotifyType.ErrorMessage);
                        break;

                    case DeviceTriggerResult.DeniedBySystem:
                        // The system can deny a task request if the system-wide DeviceUse task limit is reached.
                        rootPage.NotifyUser("The system has denied the background task request", NotifyType.ErrorMessage);
                        break;

                    default:
                        rootPage.NotifyUser("Could not start the background task: " + deviceTriggerResult, NotifyType.ErrorMessage);
                        break;
                }
            }
            catch (InvalidOperationException)
            {
                // If toggling quickly between 'Disable' and 'Enable', the previous task
                // could still be in the process of cleaning up.
                rootPage.NotifyUser("A previous background task is still running, please wait for it to exit", NotifyType.ErrorMessage);
                FindAndCancelExistingBackgroundTask();
            }

            return started;
        }
        /// <summary>
        /// This is the background task completion handler.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnBackgroundTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
        {
            // Dispatch to the UI thread to display the output.
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                // An exception may be thrown if an error occurs in the background task.
                try
                {
                    e.CheckResult();
                    if (ApplicationData.Current.LocalSettings.Values.ContainsKey("TaskCancelationReason"))
                    {
                        string cancelationReason = (string)ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"];
                        rootPage.NotifyUser("Background task was stopped, reason: " + cancelationReason, NotifyType.StatusMessage);
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Exception in background task: " + ex.Message, NotifyType.ErrorMessage);
                }

                _refreshTimer.Stop();
            });

            // Unregister the background task and let the remaining task finish until completion.
            if (null != _deviceUseBackgroundTaskRegistration)
            {
                _deviceUseBackgroundTaskRegistration.Unregister(false);
                _deviceUseBackgroundTaskRegistration = null;
            }
        }
 private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     BackgroundMediaPlayer.Shutdown();
     _deferral.Complete();
 }
        private async void RegTask_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            string json = await readStringFromLocalFile("parking.json");

            ParkingResult[] result = JsonConvert.DeserializeObject<ParkingResult[]>(json);

            foreach(var parking in result)
            {
                if (parking.parkingStatus == null)
                    continue;

                points.Add(new PointOfInterest()
                {
                    DisplayName = parking.name,
                    FreePlaces = parking.parkingStatus.availableCapacity,
                    Location = new Geopoint(new BasicGeoposition()
                    {
                        Latitude = parking.latitude,
                        Longitude = parking.longitude
                    }),
                    ParkingResult = parking
                });
            }
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, RefreshUI);
        }
 /// <summary>
 /// Handle background task completion.
 /// </summary>
 /// <param name="task">The task that is reporting completion.</param>
 /// <param name="e">Arguments of the completion report.</param>
 private async void OnBackgroundTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs eventArgs)
 {
     // We get the advertisement(s) processed by the background task
     if (ApplicationData.Current.LocalSettings.Values.Keys.Contains(taskName))
     {
         string backgroundMessage = (string) ApplicationData.Current.LocalSettings.Values[taskName];
         // Serialize UI update to the main UI thread
         await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
         {
             // Display these information on the list
             ReceivedAdvertisementListBox.Items.Add(backgroundMessage);
         });
     }
 }
示例#19
0
        private void OnBackgroundTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            args.CheckResult(); // TODO: What kind of errors does this report?
            Debug.WriteLine(sender); // BackgroundTaskRegistration
            string instanceIdString = args.InstanceId.ToString();

            if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(instanceIdString))
            {
                // This task didn't schedule a download.
                return;
            }

            Guid transferGuid = (Guid)ApplicationData.Current.LocalSettings.Values[instanceIdString];
            Debug.WriteLine("Background task completed! Last download was {0}", transferGuid);
        }
示例#20
0
 /// <summary>
 /// Updates the UI with the progress of the sync
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private async void OnSyncWithDeviceProgress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args)
 {
     await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
         new DispatchedHandler(() =>
         {
             SyncProgressBar.Value = args.Progress;
         }));
 }
 private void Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     defferal.Complete();
 }
示例#22
0
 /// <summary>
 /// Indicate that the background task is completed.
 /// </summary>       
 private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     logger.LogMessage($"Background Audio Task {sender.TaskId} Completed...");
     Dispose();
 }
示例#23
0
        /// <summary>
        /// Registers for background task that will write to the device.
        /// </summary>
        private void SetupBackgroundTask()
        {
            // Create background task to write
            var backgroundTaskBuilder = new BackgroundTaskBuilder();

            backgroundTaskBuilder.Name = SyncBackgroundTaskInformation.Name;
            backgroundTaskBuilder.TaskEntryPoint = SyncBackgroundTaskInformation.TaskEntryPoint;
            backgroundTaskBuilder.SetTrigger(syncBackgroundTaskTrigger);
            backgroundSyncTaskRegistration = backgroundTaskBuilder.Register();

            // Make sure we're notified when the task completes or if there is an update
            backgroundSyncTaskRegistration.Completed += new BackgroundTaskCompletedEventHandler(OnSyncWithDeviceCompleted);
            backgroundSyncTaskRegistration.Progress += new BackgroundTaskProgressEventHandler(OnSyncWithDeviceProgress);
        }
        /// <summary>
        /// This is the click handler for the 'Disable' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ScenarioDisable(object sender, RoutedEventArgs e)
        {
            Window.Current.VisibilityChanged -= new WindowVisibilityChangedEventHandler(VisibilityChanged);

            ScenarioEnableButton.IsEnabled = true;
            ScenarioDisableButton.IsEnabled = false;

            _refreshTimer.Stop();

            if (null != _deviceUseBackgroundTaskRegistration)
            {
                // Cancel and unregister the background task from the current app session.
                _deviceUseBackgroundTaskRegistration.Unregister(true);
                _deviceUseBackgroundTaskRegistration = null;
            }
            else
            {
                // Cancel and unregister the background task from the previous app session.
                FindAndCancelExistingBackgroundTask();
            }

            rootPage.NotifyUser("Background task was canceled", NotifyType.StatusMessage);
        }
示例#25
0
        /// <summary>
        /// Reopen the device after the background task is done syncing. Notify the UI of how many bytes we wrote to the device.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void OnSyncWithDeviceCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            // Exception may be thrown if an error occurs during running the background task
            args.CheckResult();

            await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                new DispatchedHandler(async () =>
                {
                    // Reopen the device once the background task is completed
                    await EventHandlerForDevice.Current.OpenDeviceAsync(syncDeviceInformation, syncDeviceSelector);

                    syncDeviceInformation = null;
                    syncDeviceSelector = null;

                    var taskCompleteStatus = (String)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskStatus];

                    if (taskCompleteStatus == SyncBackgroundTaskInformation.TaskCompleted)
                    {
                        UInt32 totalBytesWritten = (UInt32)ApplicationData.Current.LocalSettings.Values[LocalSettingKeys.SyncBackgroundTaskResult];

                        rootPage.NotifyUser("Sync: Wrote " + totalBytesWritten.ToString() + " bytes to the device", NotifyType.StatusMessage);
                    }
                    else if (taskCompleteStatus == SyncBackgroundTaskInformation.TaskCanceled)
                    {
                        rootPage.NotifyUser("Syncing was canceled", NotifyType.StatusMessage);
                    }

                    // Remove all local setting values
                    ApplicationData.Current.LocalSettings.Values.Clear();

                    isSyncing = false;

                    UpdateButtonStates();
                }));

            // Unregister the background task and let the remaining task finish until completion
            if (backgroundSyncTaskRegistration != null)
            {
                backgroundSyncTaskRegistration.Unregister(false);
            }
        }
示例#26
0
 private void OnBackgroundTaskProgress(BackgroundTaskRegistration sender, BackgroundTaskProgressEventArgs args)
 {
     Debug.WriteLine("Sender si {0}", sender);
     Debug.WriteLine("Progress is {0}", args.Progress);
 }
 /// <summary>
 /// Handle background task completion.
 /// </summary>
 /// <param name="task">The task that is reporting completion.</param>
 /// <param name="e">Arguments of the completion report.</param>
 private async void OnBackgroundTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs eventArgs)
 {
     // We get the status changed processed by the background task
     if (ApplicationData.Current.LocalSettings.Values.Keys.Contains(taskName))
     {
         string backgroundMessage = (string) ApplicationData.Current.LocalSettings.Values[taskName];
         // Serialize UI update to the main UI thread
         await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
         {
             // Display the status change
             PublisherStatusBlock.Text = backgroundMessage;
         });
     }
 }
 /// <summary>
 /// Called when background task defferal is completed.  This can happen for a number of reasons (both expected and unexpected).  
 /// IF this is expected, we'll notify the user.  If it's not, we'll show that this is an error.  Finally, clean up the connection by calling Disconnect().
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 private async void OnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     var settings = ApplicationData.Current.LocalSettings;
     if (settings.Values.ContainsKey("TaskCancelationReason"))
     {
         await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
         {
             statusTextBlock.Text = "ERROR: Task cancelled unexpectedly - reason: " + settings.Values["TaskCancelationReason"].ToString();
         });
     }
     else
     {
         await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
         {
             statusTextBlock.Text = "STATUS: Background task completed";
         });
     }
     try
     {
         args.CheckResult();
     }
     catch (Exception ex)
     {
         throw;
         //rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
     }
     Disconnect();
 }
 /// <summary>
 /// Indicate that the background task is completed.
 /// </summary>       
 void TaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     Debug.WriteLine("MyBackgroundAudioTask " + sender.TaskId + " Completed...");
     deferral.Complete();
 }
 void liveTileUpdater_BackgroundTaskCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
 {
     DispatchUpdateUI();
 }