Ejemplo n.º 1
0
        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);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        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);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public static async void RegisterAndRunAsync()
        {
            var taskName = typeof(CheckHeartRateInBackgroundTask).Name;
            IBackgroundTaskRegistration checkHeartRateInBackground = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(t => t.Name == taskName);

            if (band.IsConnected() && band.Identity.IsAuthenticated())
            {
                if (checkHeartRateInBackground != null)
                {
                    checkHeartRateInBackground.Unregister(true);
                }

                var deviceTrigger = new DeviceUseTrigger();
                var deviceInfo    = await band.Identity.GetPairedBand();

                var taskBuilder = new BackgroundTaskBuilder
                {
                    Name               = taskName,
                    TaskEntryPoint     = typeof(CheckHeartRateInBackgroundTask).ToString(),
                    IsNetworkRequested = false
                };

                taskBuilder.SetTrigger(deviceTrigger);
                BackgroundTaskRegistration task = taskBuilder.Register();

                await deviceTrigger.RequestAsync(deviceInfo.Id);
            }
        }
        private static async Task BuildBandDataTask(string taskName, string deviceId)
        {
            var taskBuilder = new BackgroundTaskBuilder {
                Name = BandDataTaskId, TaskEntryPoint = taskName
            };

            DeviceUseTrigger = new DeviceUseTrigger();

            taskBuilder.SetTrigger(DeviceUseTrigger);

            taskBuilder.Register();

            var triggerResult = await DeviceUseTrigger.RequestAsync(deviceId);

            switch (triggerResult)
            {
            case DeviceTriggerResult.Allowed:
                return;

            case DeviceTriggerResult.DeniedByUser:
                throw new InvalidOperationException("Cannot start the background task. Access denied by user.");

            case DeviceTriggerResult.DeniedBySystem:
                throw new InvalidOperationException("Cannot start the background task. Access denied by system.");

            case DeviceTriggerResult.LowBattery:
                throw new InvalidOperationException("Cannot start the background task. Low battery.");
            }
        }
        public static async void RegisterAndRunAsync(DeviceInformation devInfo)
        {
            var taskName = typeof(CheckHeartRateInBackgroundTask).ToString();

            IBackgroundTaskRegistration checkHeartRateInBackground = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(t => t.Name == taskName);

            if (band.IsConnected() && band.Identity.IsAuthenticated())
            {
                if (checkHeartRateInBackground != null)
                {
                    // if the task is already executing, unregister it
                    checkHeartRateInBackground.Unregister(true);
                }

                var devTrigger  = new DeviceUseTrigger();
                var taskBuilder = new BackgroundTaskBuilder {
                    Name               = taskName,
                    TaskEntryPoint     = typeof(CheckHeartRateInBackgroundTask).ToString(),
                    IsNetworkRequested = false
                };

                taskBuilder.SetTrigger(devTrigger);

                BackgroundTaskRegistration task = taskBuilder.Register();
                task.Completed += Task_Completed;
                task.Progress  += Task_Progress;
                await devTrigger.RequestAsync(devInfo.Id);
            }
        }
        /// <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_DeviceUse_TaskName,
                TaskEntryPoint = SampleConstants.Scenario1_DeviceUse_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);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Starts the background task that syncs with the device
        ///
        /// The trigger.RequestAsync() must be started on the UI thread because of the prompt that appears. The caller of StartSyncBackgroundTaskAsync()
        /// is responsible for running this method in the UI thread.
        /// </summary>
        /// <returns></returns>
        private Task <DeviceTriggerResult> StartSyncBackgroundTaskAsync()
        {
            // Save the current device information so that we can reopen it after syncing
            syncDeviceInformation = EventHandlerForDevice.Current.DeviceInformation;
            syncDeviceSelector    = EventHandlerForDevice.Current.DeviceSelector;

            // Allow the background task to open the device and sync with it.
            // We must close the device because Background tasks need to create new handle to the device and cannot reuse the one from this app.
            // Since the device is opened exclusively, the app must close the device before the background task can use the device.
            EventHandlerForDevice.Current.CloseDevice();

            return(syncBackgroundTaskTrigger.RequestAsync(syncDeviceInformation.Id).AsTask());
        }
Ejemplo n.º 8
0
        private async Task ActivateBackground()
        {
            _deviceUseTrigger = new DeviceUseTrigger();
            accessStatus      = await BackgroundExecutionManager.RequestAccessAsync();

            if ((BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity == accessStatus) ||
                (BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity == accessStatus))
            {
                var backgroundTaskBuilder = new BackgroundTaskBuilder()
                {
                    Name           = "BandTaskInBackground",
                    TaskEntryPoint = "BandBackgroundTask.BandTaskInBackground"
                };
                backgroundTaskBuilder.SetTrigger(_deviceUseTrigger);
                _deviceUseBackgroundTaskRegistration           = backgroundTaskBuilder.Register();
                _deviceUseBackgroundTaskRegistration.Progress += _deviceUseBackgroundTaskRegistration_Progress;
                var triggerResult = await _deviceUseTrigger.RequestAsync(device.Id);
            }
        }
Ejemplo n.º 9
0
        private async Task <bool> StartAccelerometerBackGroundTask(String deviceId)
        {
            bool started = false;

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

#warning background task seems to be run from here

                switch (accelerometerTriggerResult)
                {
                case DeviceTriggerResult.Allowed:
                    Status  = "Background task started";
                    started = true;
                    break;

                case DeviceTriggerResult.LowBattery:
                    Error = "Insufficient battery to run the background task";
                    break;

                case DeviceTriggerResult.DeniedBySystem:
                    // The system can deny a task request if the system-wide DeviceUse task limit is reached.
                    Error = "The system has denied the background task request";
                    break;

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

            return(started);
        }
Ejemplo n.º 10
0
        public async Task StartBackgroundTask(Initiator InitiatedBy)
        {
            /* PebbleConnector _pc = PebbleConnector.GetInstance();
             * int Handler = await _pc.Connect(-1);
             *
             * return;*/
            var result = await BackgroundExecutionManager.RequestAccessAsync();

            if (result == BackgroundAccessStatus.Denied)
            {
                return;
            }

            PebbleConnector.SetBackgroundTaskRunningStatus(InitiatedBy);

            if (!await IsBackgroundTaskRunning())
            {
                backgroundSyncTaskRegistration = FindSyncTask();
                while (backgroundSyncTaskRegistration != null)
                {
                    backgroundSyncTaskRegistration.Unregister(true);

                    backgroundSyncTaskRegistration = FindSyncTask();
                }

                //if (backgroundSyncTaskRegistration == null)
                // {
                syncBackgroundTaskTrigger = new DeviceUseTrigger();

                // Create background task to write
                var backgroundTaskBuilder = new BackgroundTaskBuilder();

                backgroundTaskBuilder.Name           = Constants.BackgroundCommunicationTaskName;
                backgroundTaskBuilder.TaskEntryPoint = Constants.BackgroundCommunicationTaskEntry;
                backgroundTaskBuilder.SetTrigger(syncBackgroundTaskTrigger);
                backgroundSyncTaskRegistration = backgroundTaskBuilder.Register();


                // }


                try
                {
                    PebbleDevice _AssociatedDevice = PebbleDevice.LoadAssociatedDevice();
                    if (_AssociatedDevice != null)
                    {
                        var _device = await BluetoothDevice.FromIdAsync(_AssociatedDevice.ServiceId);

                        //var device = (await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(new Guid(Constants.PebbleGuid))))).FirstOrDefault(y => y.Name.ToLower().Contains("pebble"));

                        if (_device == null)
                        {
                            throw new OperationCanceledException("Is bluetooth enabled and the Pebble Time paired?");
                        }

                        //DeviceTriggerResult x = await syncBackgroundTaskTrigger.RequestAsync(device.Id);

                        var abc = syncBackgroundTaskTrigger.RequestAsync(_device.DeviceId).AsTask();
                        var x   = await abc;

                        System.Diagnostics.Debug.WriteLine("DeviceTriggerResult: " + x.ToString());

                        if (x != DeviceTriggerResult.Allowed)
                        {
                            throw new Exception(x.ToString());
                        }
                    }
                }
                catch (Exception exc)
                {
                    if (exc.GetType() == typeof(System.OperationCanceledException))
                    {
                        throw exc;
                    }
                    if (exc.GetType() != typeof(System.InvalidOperationException))
                    {
                        throw new Exception("Background communication task can't be started: " + exc.Message);
                    }
                    throw new Exception("Unexpected error: " + exc.Message);
                }
            }
        }
 private static async Task<bool> RequestDeviceUseTriggerAsync(string deviceId, DeviceUseTrigger deviceUseTrigger, string taskName, string arguments)
 {
     try
     {
         DeviceTriggerResult deviceTriggerResult = await deviceUseTrigger.RequestAsync(deviceId, arguments);
         switch (deviceTriggerResult)
         {
             case DeviceTriggerResult.Allowed:
                 //ShowNotifyMessage("Background Task wurde gestartet.", NotifyLevel.Info);
                 return true;
             case DeviceTriggerResult.DeniedBySystem:
                 //ShowNotifyMessage("Background Task wurde vom System verweigert.", NotifyLevel.Warn);
                 break;
             case DeviceTriggerResult.DeniedByUser:
                 //ShowNotifyMessage("Background Task wurde vom Nutzer verweigert.", NotifyLevel.Warn);
                 break;
             case DeviceTriggerResult.LowBattery:
                 //ShowNotifyMessage("Background Task wurde wegen geringer Batterie verweigert.", NotifyLevel.Warn);
                 break;
         }
     }
     catch (InvalidOperationException)
     {
         DeregisterBackgroundTask(taskName);
     }
     return false;
 }
        private static async Task BuildBandDataTask(string taskName, string deviceId)
        {
            var taskBuilder = new BackgroundTaskBuilder { Name = BandDataTaskId, TaskEntryPoint = taskName };

            DeviceUseTrigger = new DeviceUseTrigger();

            taskBuilder.SetTrigger(DeviceUseTrigger);

            taskBuilder.Register();

            var triggerResult = await DeviceUseTrigger.RequestAsync(deviceId);

            switch (triggerResult)
            {
                case DeviceTriggerResult.Allowed:
                    return;
                case DeviceTriggerResult.DeniedByUser:
                    throw new InvalidOperationException("Cannot start the background task. Access denied by user.");
                case DeviceTriggerResult.DeniedBySystem:
                    throw new InvalidOperationException("Cannot start the background task. Access denied by system.");
                case DeviceTriggerResult.LowBattery:
                    throw new InvalidOperationException("Cannot start the background task. Low battery.");
            }
        }