//
        // Handles background task cancellation.
        //
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            //
            // Indicate that the background task is canceled.
            //

        }
Esempio n. 2
0
        /// <summary>
        ///     Handles background task cancellation. Task cancellation happens due to:
        ///     1. Another Media app comes into foreground and starts playing music
        ///     2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        ///     In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                TaskStarted.Reset();

                // Dispose
                _playerWrapper.Dispose();
                _smtcWrapper.Dispose();
                _foregroundMessenger.Dispose();

                // shutdown media pipeline
                BackgroundMediaPlayer.Shutdown();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            _settingsUtility.Write(ApplicationSettingsConstants.BackgroundTaskState,
                BackgroundTaskState.Canceled);

            _deferral.Complete(); // signals task completion. 
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Esempio n. 3
0
 //
 // Handles background task cancellation.
 //
 private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     //
     // Indicate that the background task is canceled.
     //
     Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
 }
Esempio n. 4
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     _clock.Dispose();
     _timer2.Cancel();
     _timer3.Cancel();
     _deferral.Complete();
 }
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     var properties = new Dictionary<string, string>();
     properties.Add("Reason", reason.ToString());
     StartupTask.WriteTelemetryEvent("AppServicesBackgroundTask_Canceled", properties);
     serviceDeferral.Complete();
 }
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            _cancelRequested = true;
            _cancelReason = reason;

            Debug.WriteLine($"Background '{sender.Task.Name}' Cancel Requested...");
        }
Esempio n. 7
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     if (this.deferral != null)
     {
         this.deferral.Complete();
     }
 }
Esempio n. 8
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            this.SendToForeground(CommunicationConstants.BackgroundTaskStopped);

            try
            {
                ApplicationSettings.BackgroundTaskResumeSongTime.Save(BackgroundMediaPlayer.Current.Position.TotalSeconds);
                /*
                //save state
                ApplicationSettingsHelper.SaveSettingsValue(Constants.CurrentTrack, Playlist.CurrentTrackName);
                ApplicationSettingsHelper.SaveSettingsValue(Constants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskCancelled);
                ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
                backgroundtaskrunning = false;
                //unsubscribe event handlers
                systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;
                Playlist.TrackChanged -= playList_TrackChanged;

                //clear objects task cancellation can happen uninterrupted
                playlistManager.ClearPlaylist();
                playlistManager = null;
                 */
                this.mediaControls.ButtonPressed -= mediaControls_ButtonPressed;
                playlistManager = null;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            if (_deferral != null)
                _deferral.Complete();
        }
Esempio n. 9
0
 private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     if (_cts != null)
     {
         _cts.Cancel();
         _cts = null;
     }
 }
Esempio n. 10
0
 private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     //
     // Indicate that the background task is canceled.
     //
     _cancelRequested = true;
     _cancelReason = reason;
 }
Esempio n. 11
0
		private void canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
		{
			deferral.Complete();
			deferral = null;
			timer.Tick -= timerTick;
			timer = null;
			controller = null;
		}
Esempio n. 12
0
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     if (this.serviceDeferral != null)
     {
         //Complete the service deferral
         this.serviceDeferral.Complete();
     }
 }
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     BackgroundMediaPlayer.Shutdown();
     if (deferral != null)
     {
         deferral.Complete();
     }
 }
Esempio n. 14
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     if (mDeferral != null)
     {
         mDeferral.Complete();
     }
     CurrentOperation.PhoneCallTaskDeferral = null;
 }
        /// <summary> 
        /// Called when the background task is canceled by the app or by the system.
        /// </summary> 
        /// <param name="sender"></param>
        /// <param name="reason"></param>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"] = reason.ToString();
            ApplicationData.Current.LocalSettings.Values["SampleCount"] = _sampleCount;
            ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = false;

            // Complete the background task (this raises the OnCompleted event on the corresponding BackgroundTaskRegistration).
            _deferral.Complete();
        }
Esempio n. 16
0
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     Debug.WriteLine("App service closed due to an unexpected failure; Cleaning up");
     if (this.serviceDeferral != null)
     {
         //Complete the service deferral
         this.serviceDeferral.Complete();
     }
 }
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     System.Diagnostics.Debug.WriteLine("Task cancelled, clean up");
     if (this.serviceDeferral != null)
     {
         //Complete the service deferral
         this.serviceDeferral.Complete();
     }
 }
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            if (_deferral != null)
            {
                _deferral.Complete();
            }

            Current.RTCTaskDeferral = null;
        }
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            LiveTile.UpdateSecondaryTile("--");
            System.Diagnostics.Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested because " + reason);

            if (!reason.Equals(BackgroundTaskCancellationReason.Abort))
            {
                ToastHelper.PopToast("Background Cancelled", "Background Task Cancelled, reason: " + reason + ", please re-start the applications.");
            }
        }
Esempio n. 20
0
        private async void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            var properties = new Dictionary<string, string>();
            properties.Add("Reason", reason.ToString());
            WriteTelemetryEvent("App_Shutdown", properties);

            await s_radioManager.Dispose();

            deferral.Complete();
        }
        //
        // Handles background task cancellation.
        //
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            //
            // Indicate that the background task is canceled.
            //
            var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
            settings.Values[sender.Task.TaskId.ToString()] = "Canceled";

            Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
        }
        private void OnCanceled(IBackgroundTaskInstance taskInstance, BackgroundTaskCancellationReason reason)
        {
            cancelReason = reason;
            cancelRequested = true;

            ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"] = cancelReason.ToString();
            ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = false;
            
            // Complete the background task (this raises the OnCompleted event on the corresponding BackgroundTaskRegistration). 
            deferral.Complete();
        }
        /// <summary> 
        /// Called when the background task is canceled by the app or by the system.
        /// </summary> 
        /// <param name="sender"></param>
        /// <param name="reason"></param>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"] = reason.ToString();
            ApplicationData.Current.LocalSettings.Values["SampleCount"] = SampleCount;
            ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = false;

            if (null != Accelerometer)
            {
                Accelerometer.ReadingChanged -= new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged);
                Accelerometer.ReportInterval = 0;
            }

            // Complete the background task (this raises the OnCompleted event on the corresponding BackgroundTaskRegistration).
            Deferral.Complete();
        }
Esempio n. 24
0
        /// <summary>
        /// Complete the deferral when the task is cancelled.
        /// </summary>
        /// <param name="sender">the background task instance</param>
        /// <param name="reason">the cancellation reason</param>
        private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            _canceled = true;

            if (_action != null && _action.Status == AsyncStatus.Started)
            {
                _action.Cancel();
            }

            if (this.backgroundTaskDeferral != null)
            {
                // Complete the service deferral.
                this.backgroundTaskDeferral.Complete();

                this.backgroundTaskDeferral = null;
            }
        }
Esempio n. 25
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            lock (Locker)
            {
                try
                {
                    if ((sender.TriggerDetails as AppServiceTriggerDetails)?.AppServiceConnection is AppServiceConnection DisConnection)
                    {
                        try
                        {
                            DisConnection.RequestReceived -= Connection_RequestReceived;

                            if (ServiceAndClientConnections.FirstOrDefault((Pair) => Pair.Server == DisConnection || Pair.Client == DisConnection) is ServerAndClientPair ConnectionPair)
                            {
                                if (ConnectionPair.Server == DisConnection)
                                {
                                    ConnectionPair.Server = null;
                                }
                                else
                                {
                                    ServiceAndClientConnections.Remove(ConnectionPair);

                                    ConnectionPair.Client = null;

                                    ConnectionPair.Server?.SendMessageAsync(new ValueSet {
                                        { "ExecuteType", "Execute_Exit" }
                                    }).AsTask().ConfigureAwait(false).GetAwaiter().GetResult();
                                }
                            }
                        }
                        finally
                        {
                            DisConnection.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Error thrown in CommuniteService: {ex.Message}");
                }
                finally
                {
                    Deferral.Complete();
                }
            }
        }
Esempio n. 26
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            switch (reason)
            {
            case BackgroundTaskCancellationReason.Abort:
                //app unregistered background task (amoung other reasons).
                break;

            case BackgroundTaskCancellationReason.Terminating:
                //system shutdown
                break;

            case BackgroundTaskCancellationReason.LoggingOff:
                break;

            case BackgroundTaskCancellationReason.ServicingUpdate:
                break;

            case BackgroundTaskCancellationReason.IdleTask:
                break;

            case BackgroundTaskCancellationReason.Uninstall:
                break;

            case BackgroundTaskCancellationReason.ConditionLoss:
                break;

            case BackgroundTaskCancellationReason.SystemPolicy:
                break;

            case BackgroundTaskCancellationReason.ExecutionTimeExceeded:
                break;

            case BackgroundTaskCancellationReason.ResourceRevocation:
                break;

            case BackgroundTaskCancellationReason.EnergySaver:
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(reason), reason, null);
            }

            this.m_backgroundTaskDeferral.Complete();
        }
Esempio n. 27
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            try
            {
                if ((sender.TriggerDetails as AppServiceTriggerDetails)?.AppServiceConnection is AppServiceConnection DisConnection)
                {
                    try
                    {
                        DisConnection.RequestReceived -= Connection_RequestReceived;

                        lock (Locker)
                        {
                            if (PairedConnections.TryRemove(DisConnection, out AppServiceConnection ServerConnection))
                            {
                                Task.WaitAny(ServerConnection.SendMessageAsync(new ValueSet {
                                    { "ExecuteType", "Execute_Exit" }
                                }).AsTask(), Task.Delay(2000));
                            }
                            else if (PairedConnections.FirstOrDefault((Con) => Con.Value == DisConnection).Key is AppServiceConnection ClientConnection)
                            {
                                if (PairedConnections.TryRemove(ClientConnection, out _))
                                {
                                    Task.WaitAny(ClientConnection.SendMessageAsync(new ValueSet {
                                        { "ExecuteType", "FullTrustProcessExited" }
                                    }).AsTask(), Task.Delay(2000));
                                    ClientConnection.Dispose();
                                }
                            }
                        }
                    }
                    finally
                    {
                        DisConnection.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error was threw in CommunicateService: {ex.Message}");
            }
            finally
            {
                Deferral.Complete();
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Вызывается при отмене фоновой задачи.
        /// </summary>
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
#if DEBUG
            Debug.WriteLine("AudioTask cancel requested.");
#endif
            SendMessageToForeground(AppConstants.PlayerTaskRunning, false);
            SettingsHelper.Set(AppConstants.PlayerTaskRunning, false);
            _isTaskRunning = false;

            BackgroundMediaPlayer.MessageReceivedFromForeground -= OnMessageReceivedFromForeground;
            _player.CurrentStateChanged -= Player_CurrentStateChanged;
            _manager.TrackChanged       -= Manager_TrackChanged;
            _controls.ButtonPressed     -= Controls_ButtonPressed;
            _manager = null;
            BackgroundMediaPlayer.Shutdown();

            _deferral.Complete();
        }
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to :
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                systemmediatransportcontrol.ButtonPressed   -= systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
        public void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            Debug.WriteLine("BackgroundAudioRun.OnCanceled() " + _id + " reason " + reason);

            try
            {
                var mediaPlayerManager = _mediaPlayerManager;

                if (null == mediaPlayerManager)
                {
                    BackgroundSettings.Position = null;
                }
                else
                {
                    var mediaPlayer = _mediaPlayerManager.MediaPlayer;

                    if (null != mediaPlayer && mediaPlayer.CanSeek)
                    {
                        var position = mediaPlayer.Position;

                        BackgroundSettings.Position = position;
                    }
                    else
                    {
                        BackgroundSettings.Position = null;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("BackgroundAudioRun.OnCanceled() position store failed: " + ex.ExtendedMessage());
            }

            _completionSource.TrySetResult(null);

            try
            {
                Cancel();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("BackgroundAudioRun.OnCanceled() cancel failed: " + ex.ExtendedMessage());
            }
        }
Esempio n. 31
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender,
                                           BackgroundTaskCancellationReason reason)
        {
            _isClosing = true;

            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }

            // if (_handler != null)
            {
                //     _handler.Dispose();
                //     _handler = null;
            }

            sender.GetDeferral().Complete();
        }
Esempio n. 32
0
        /// <summary>
        /// This happens when an app closes its connection normally.
        /// </summary>
        private async void OnTaskCancelled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            System.Diagnostics.Debug.WriteLine("MessageRelay was cancelled, removing " + _thisConnectionGuid + " from the list of active connections.");
            RemoveConnection(_thisConnectionGuid);

            if (Connections.Count == 1)
            {
                // Last open connection is the fulltrust process, lets close it
                // This should be done better and handle fulltrust process crashes
                var value = new ValueSet() { { "Arguments", "Terminate" } };
                await SendMessageAsync(Connections.Single(), value);
            }

            if (_backgroundTaskDeferral != null)
            {
                _backgroundTaskDeferral.Complete();
                _backgroundTaskDeferral = null;
            }
        }
Esempio n. 33
0
        //volatile bool _cancelRequested = false;
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
#if LOG_STEP
            var tbtLogC = await ApplicationData.Current.LocalFolder.CreateFileAsync("TbtCancelled.txt", CreationCollisionOption.ReplaceExisting);

            using (var s = await tbtLogC.OpenStreamForWriteAsync())
            {
                var sw = new StreamWriter(s);
                var ct = DateTime.Now;
                sw.WriteLine("Background task cancellation time: " + ct.ToString());
                sw.Flush();
            }
#endif
            //
            // Indicate that the background task is canceled.
            //
            //_cancelRequested = true;
            deferral.Complete();
        }
Esempio n. 34
0
        /// <summary>
        /// Periodically check if there's a new message and if there is, send it over the socket
        /// </summary>
        /// <param name="timer"></param>

        private async void PeriodicTimerCallback(ThreadPoolTimer timer)
        {
            if (!cancelRequested)
            {
                string message = (string)ApplicationData.Current.LocalSettings.Values["SendMessage"];
                if (!string.IsNullOrEmpty(message))
                {
                    try
                    {
                        // Make sure that the connection is still up and there is a message to send
                        if (socket != null)
                        {
                            writer.WriteUInt32((uint)message.Length);
                            writer.WriteString(message);
                            await writer.StoreAsync();

                            ApplicationData.Current.LocalSettings.Values["SendMessage"] = null;
                        }
                        else
                        {
                            cancelReason = BackgroundTaskCancellationReason.ConditionLoss;
                            deferral.Complete();
                        }
                    }
                    catch (Exception ex)
                    {
                        ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"] = ex.Message;
                        ApplicationData.Current.LocalSettings.Values["SendMessage"]           = null;
                        deferral.Complete();
                    }
                }
            }
            else
            {
                // Timer clean up
                periodicTimer.Cancel();
                //
                // Write to LocalSettings to indicate that this background task ran.
                //
                ApplicationData.Current.LocalSettings.Values["TaskCancelationReason"] = cancelReason.ToString();
            }
        }
Esempio n. 35
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            //a few reasons that you may be interested in.
            switch (reason)
            {
                case BackgroundTaskCancellationReason.Abort:
                    //app unregistered background task (amoung other reasons).
                    break;
                case BackgroundTaskCancellationReason.Terminating:
                    //system shutdown
                    break;
                case BackgroundTaskCancellationReason.ConditionLoss:
                    break;
                case BackgroundTaskCancellationReason.SystemPolicy:
                    break;
            }
            http.Dispose();

            _defferal.Complete();
        }
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to :
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            SendBackgroundTaskIsStopping();

            try
            {
                backgroundtaskrunning = false;
                //unsubscribe event handlers
                systemmediatransportcontrol.ButtonPressed   -= systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Esempio n. 37
0
        public static CancellationReason ConvertCancellationReason(this BackgroundTaskCancellationReason reason)
        {
            switch (reason)
            {
            case BackgroundTaskCancellationReason.Abort:
                return(CancellationReason.Abort);

            case BackgroundTaskCancellationReason.Terminating:
                return(CancellationReason.Terminating);

            case BackgroundTaskCancellationReason.LoggingOff:
                return(CancellationReason.LoggingOff);

            case BackgroundTaskCancellationReason.ServicingUpdate:
                return(CancellationReason.ServicingUpdate);

            case BackgroundTaskCancellationReason.IdleTask:
                return(CancellationReason.IdleTask);

            case BackgroundTaskCancellationReason.Uninstall:
                return(CancellationReason.Uninstall);

            case BackgroundTaskCancellationReason.ConditionLoss:
                return(CancellationReason.ConditionLoss);

            case BackgroundTaskCancellationReason.SystemPolicy:
                return(CancellationReason.SystemPolicy);

            case BackgroundTaskCancellationReason.ExecutionTimeExceeded:
                return(CancellationReason.ExecutionTimeExceeded);

            case BackgroundTaskCancellationReason.ResourceRevocation:
                return(CancellationReason.ResourceRevocation);

            case BackgroundTaskCancellationReason.EnergySaver:
                return(CancellationReason.EnergySaver);

            default:
                throw new ArgumentOutOfRangeException(nameof(reason), reason, null);
            }
        }
        /// <summary>
        /// 后台任务取消的event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="reason">取消原因</param>
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            Debug.WriteLine("BackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");

            try
            {
                backgroundTaskStarted.Reset();

                //保存前后台任务状态和歌曲播放信息
                BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.TRACK_INDEX, playbackList.CurrentItemIndex);
                BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.POSITION, BackgroundMediaPlayer.Current.Position.ToString());
                BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.BACKGROUND_TASK_STATE, BackgroundTaskState.Canceled.ToString());
                BackgroundAudioSettingsHelper.SetValue(BackgroundAudioSettingsConstants.APP_STATE, Enum.GetName(typeof(AppState), foregroundAppState));

                //清空播放列表
                if (playbackList != null)
                {
                    //playbackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
                    playbackList = null;
                }

                //取消注册时间
                BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground;
                smtc.ButtonPressed   -= Smtc_ButtonPressed;
                smtc.PropertyChanged -= Smtc_PropertyChanged;

                //发送后台任务停止消息给前台
                MessageService.SendMessageToForeground(new BackgroundAudioTaskStopedMessage());
                //关闭后台播放器
                BackgroundMediaPlayer.Shutdown();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString() + "  " + ex.Message);
            }
            finally
            {
                deferral.Complete();
                Debug.WriteLine("BackgroundAudioTask Cancel Completed");
            }
        }
        private void OnAppServicesCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            AppServiceTriggerDetails appService = sender.TriggerDetails as AppServiceTriggerDetails;

            try
            {
                CurrentConnectionIndex = int.Parse(appService.AppServiceConnection.AppServiceName);
                AppServiceDeferral     = AppServiceDeferrals[CurrentConnectionIndex];
                AppServiceDeferrals.Remove(CurrentConnectionIndex);

                if (AppServiceDeferral != null)
                {
                    AppServiceDeferral.Complete();
                    AppServiceDeferral = null;
                }
            }
            catch (Exception Ex)
            {
                Debug.WriteLine("OnAppServicesCanceled error: " + Ex.Message);
            }
        }
Esempio n. 40
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            //a few reasons that you may be interested in.
            switch (reason)
            {
            case BackgroundTaskCancellationReason.Abort:
                //app unregistered background task (amoung other reasons).
                break;

            case BackgroundTaskCancellationReason.Terminating:
                //system shutdown
                break;

            case BackgroundTaskCancellationReason.ConditionLoss:
                break;

            case BackgroundTaskCancellationReason.SystemPolicy:
                break;
            }
            deferral.Complete();
        }
Esempio n. 41
0
        /// <summary>
        /// Method executed on sudden background task cancellation i.e. launching another music player
        /// </summary>
        /// <param name="sender">Background task instance</param>
        /// <param name="reason">Reason for cancellation</param>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            try
            {
                backgroundTaskStarted.Reset();

                if (currentPlaylist != null)
                {
                    currentPlaylist = null;
                }

                systemMediaTransportControl.ButtonPressed -= MediaTransportControlButtonPressed;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            taskDeferral.Complete(); // signals task completion.
        }
Esempio n. 42
0
        private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            if (this.persistenceLayer != null)
            {
                this.persistenceLayer.Save();
            }

            if (this.synchronizationManager != null)
            {
                await this.synchronizationManager.SaveAsync();
            }

            await LogService.SaveAsync();

            ReportStatus(BackgroundExecutionStatus.Cancelled);

            if (this.deferral != null)
            {
                this.deferral.Complete();
            }
        }
        /// <summary>
        /// Executes the task canceled action.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="reason">The reason.</param>
        private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            Debug.WriteLine("Background Audio Task " + sender.Task.TaskId + " cancelling");
            Debug.WriteLine("Background Audio Task cancel reason: {0}", reason);

            try
            {
                // Unsubscribe event handlers
                this.systemMediaTransportControl.ButtonPressed   -= this.OnSystemMediaTransportControlButtonPressed;
                this.systemMediaTransportControl.PropertyChanged -= this.OnSystemMediaTransportControlPropertyChanged;

                BackgroundMediaPlayer.Shutdown();
            }
            catch (Exception ex)
            {
                // TODO: Must send exception to app and the app must report to Insights
            }

            this.deferral.Complete();

            Debug.WriteLine("Background Audio Task canceled");
        }
Esempio n. 44
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            _AppTriggerDeferral?.Complete();
            _SyncDeferral?.Complete();
            _ToastDeferral?.Complete();
            _ExExecSession.Revoked -= ExExecSession_Revoked;
            _ExExecSession.Dispose();
            _ExExecSession = null;
            ToastHelper.ShowMessage($"{sender.Task.Name} has been canceled", reason.ToString());

            //switch (sender.Task.Name)
            //{
            //    case "SyncNotifications":
            //    case "SyncNotificationsApp":
            //        _SyncDeferral?.Complete();
            //        _SyncAppDeferral?.Complete();
            //        break;
            //    case "ToastNotificationBackgroundTask":
            //        _ToastActionDeferral?.Complete();
            //        break;
            //}
        }
Esempio n. 45
0
        /// <summary>
        ///     Handles background task cancellation. Task cancellation happens due to :
        ///     1. Another Media app comes into foreground and starts playing music
        ///     2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        ///     In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                //save state
                AppSettingsHelper.Write(PlayerConstants.Position,
                                        BackgroundMediaPlayer.Current.Position.ToString());
                AppSettingsHelper.Write(PlayerConstants.BackgroundTaskState,
                                        PlayerConstants.BackgroundTaskCancelled);
                AppSettingsHelper.Write(PlayerConstants.AppState,
                                        Enum.GetName(typeof(ForegroundAppStatus), _foregroundAppState));

                _backgroundtaskrunning = false;
                //unsubscribe event handlers
                _systemmediatransportcontrol.ButtonPressed   -= systemmediatransportcontrol_ButtonPressed;
                _systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;

                if (_queueManager != null)
                {
                    AppSettingsHelper.Write(PlayerConstants.CurrentTrack, QueueManager.CurrentTrack.Id);
                    QueueManager.TrackChanged -= playList_TrackChanged;

                    _queueManager = null;
                }
                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            if (_deferral != null)
            {
                _deferral.Complete(); // signals task completion.
                Debug.WriteLine("AudioPlayer Cancel complete...");
            }
        }
Esempio n. 46
0
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            try
            {
                BackgroundMediaPlayer.Current.Pause();
                BackgroundMediaPlayer.MessageReceivedFromForeground -= MessageReceivedFromForeground;

                if (shutdown)
                {
                    ApplicationSettingsHelper.SaveSettingsValue(AppConstants.Position, TimeSpan.Zero.ToString());
                }
                else
                {
                    ApplicationSettingsHelper.SaveSettingsValue(AppConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                }

                nowPlayingManager.RemoveHandlers();
                nowPlayingManager = null;

                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.BackgroundTaskState, AppConstants.BackgroundTaskCancelled);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.AppState, Enum.GetName(typeof(ForegroundTaskStatus), foregroundTaskStatus));
                backgroundTaskStatus = false;

                //unsubscribe event handlers
                systemControls.ButtonPressed   -= HandleButtonPressed;
                systemControls.PropertyChanged -= HandlePropertyChanged;
                if (!shutdown)
                {
                    BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
                }
            }
            catch (Exception ex)
            {
                NextPlayerDataLayer.Diagnostics.Logger.SaveBG("Audio Player OnCanceled " + "\n" + "Message: " + ex.Message + "\n" + "Link: " + ex.HelpLink);
                NextPlayerDataLayer.Diagnostics.Logger.SaveToFileBG();
            }
            deferral.Complete(); // signals task completion.
        }
Esempio n. 47
0
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to :
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                //save state
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.CurrentTrack, Playlist.CurrentTrackIndex);
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.Time, BackgroundMediaPlayer.Current.NaturalDuration.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.BackgroundTaskState, BackgroundAudioConstants.BackgroundTaskCancelled);
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
                backgroundtaskrunning = false;
                //unsubscribe event handlers
                systemmediatransportcontrol.ButtonPressed   -= systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;
                Playlist.TrackChanged -= playList_TrackChanged;

                //clear objects task cancellation can happen uninterrupted
                playlistManager.ResetCollection((int)ResetType.NormalReset);
                playlistManager = null;

                // Send message to foreground task (if it's around) that this task was cancelled :(
                ValueSet message = new ValueSet {
                    { BackgroundAudioConstants.BackgroundTaskCancelled, "" }
                };
                BackgroundMediaPlayer.SendMessageToForeground(message);

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral?.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Esempio n. 48
0
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to:
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("Bgt " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                backgroundTaskStarted.Reset();

                // save state
                AppSettingsHelper.SaveVal(ApplicationSettingsConstants.TrackId, GetCurrentTrackId() == null ? null : GetCurrentTrackId().ToString());
                AppSettingsHelper.SaveVal(ApplicationSettingsConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                AppSettingsHelper.SaveVal(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Canceled.ToString());
                AppSettingsHelper.SaveVal(ApplicationSettingsConstants.AppState, Enum.GetName(typeof(AppState), foregroundAppState));

                // unsubscribe from list changes
                if (_mpl != null)
                {
                    _mpl.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
                    _mpl = null;
                }

                // unsubscribe event handlers
                BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground;
                _smtc.ButtonPressed   -= smtc_ButtonPressed;
                _smtc.PropertyChanged -= smtc_PropertyChanged;

                BackgroundMediaPlayer.Shutdown();                 // shutdown media pipeline
            }
            catch (Exception ex) { Debug.WriteLine($"$#~>{ex.Message}"); if (Debugger.IsAttached)
                                   {
                                       Debugger.Break();
                                   }         /*else throw;*/
                                   MessageService.SendMessageToForeground(new ExceptionCaughtMessage(ex.Message)); }
            deferral.Complete();             // signals task completion.
            Debug.WriteLine("Bgt Cancel complete...");
        }
Esempio n. 49
0
        /// <summary>
        ///     Handles background task cancellation. Task cancellation happens due to :
        ///     1. Another Media app comes into foreground and starts playing music
        ///     2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        ///     In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                TaskStarted.Reset();
                if (_queueManager != null)
                {
                    QueueManager.TrackChanged -= playList_TrackChanged;
                    _queueManager              = null;
                }

                _appSettingsHelper.Write(PlayerConstants.BackgroundTaskState,
                                         PlayerConstants.BackgroundTaskCancelled);

                _backgroundtaskrunning = false;
                //unsubscribe event handlers
                _systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }

            if (_deferral != null)
            {
                _deferral.Complete(); // signals task completion.
                Debug.WriteLine("AudioPlayer Cancel complete...");
            }

            QueueManager.ErrorHandler -= QueueManager_ErrorHandler;
            TileUpdateManager.CreateTileUpdaterForApplication("App").Clear();
        }
        /// <summary>
        /// Associate the cancellation handler with the background task
        /// </summary>
        private void OnCentennialAppServicesCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            AppServiceTriggerDetails appService = sender.TriggerDetails as AppServiceTriggerDetails;

            this.currentConnectionIndex = Int32.Parse(appService.AppServiceConnection.AppServiceName);
            this.connection             = connections[this.currentConnectionIndex];
            this.connection.Dispose();
            connections.Remove(this.currentConnectionIndex);

            this.appServiceDeferral = appServiceDeferrals[this.currentConnectionIndex];
            appServiceDeferrals.Remove(this.currentConnectionIndex);
            this.centennialAppServiceDeferral = centennialAppServiceDeferrals[this.currentConnectionIndex];
            centennialAppServiceDeferrals.Remove(this.currentConnectionIndex);
            if (this.appServiceDeferral != null)
            {
                this.appServiceDeferral.Complete();
                this.appServiceDeferral = null;
            }
            if (this.centennialAppServiceDeferral != null)
            {
                this.centennialAppServiceDeferral.Complete();
                this.centennialAppServiceDeferral = null;
            }
        }
Esempio n. 51
0
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to:
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                _backgroundTaskStarted.Reset();

                // unsubscribe from list changes
                if (_playbackList != null)
                {
                    _playbackList.CurrentItemChanged -= PlaybackListCurrentItemChanged;
                    _playbackList = null;
                }

                // remove handlers for MediaPlayer
                BackgroundMediaPlayer.Current.CurrentStateChanged -= MediaPlayerStateChanged;
                BackgroundMediaPlayer.Current.MediaEnded          -= MediaPlayerMediaEnded;

                // unsubscribe event handlers
                BackgroundMediaPlayer.MessageReceivedFromForeground -= MessageReceivedFromForeground;
                smtc.ButtonPressed   -= AudioControlButtonPressed;
                smtc.PropertyChanged -= AudioControlPropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                telemetry.TrackException(ex, new Dictionary <string, string> {
                    { "Scenario", "BackgroundAudioCancel" }
                });
            }
            _deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Esempio n. 52
0
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to:
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("BackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                backgroundTaskStarted.Reset();

                // save state
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, GetCurrentTrackId() == null ? null : GetCurrentTrackId().ToString());
                //ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Canceled.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, Enum.GetName(typeof(AppState), foregroundAppState));

                // unsubscribe from list changes
                if (playbackList != null)
                {
                    playbackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
                    playbackList = null;
                }

                // unsubscribe event handlers
                BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground;
                smtc.ButtonPressed   -= smtc_ButtonPressed;
                smtc.PropertyChanged -= smtc_PropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("BackgroundAudioTask Cancel complete...");
        }
 private void OnAppServicesCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     _appServiceDeferral.Complete();
 }
Esempio n. 54
0
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to :
        /// 1. Another Media app comes into foreground and starts playing music 
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                //save state
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.CurrentTrack, Playlist.CurrentTrackIndex);
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.Time, BackgroundMediaPlayer.Current.NaturalDuration.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.BackgroundTaskState, BackgroundAudioConstants.BackgroundTaskCancelled);
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
                backgroundtaskrunning = false;
                //unsubscribe event handlers
                systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;
                Playlist.TrackChanged -= playList_TrackChanged;

                //clear objects task cancellation can happen uninterrupted
                playlistManager.ResetCollection((int)ResetType.NormalReset);
                playlistManager = null;

                // Send message to foreground task (if it's around) that this task was cancelled :(
                ValueSet message = new ValueSet { { BackgroundAudioConstants.BackgroundTaskCancelled, "" } };
                BackgroundMediaPlayer.SendMessageToForeground(message);

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral?.Complete(); // signals task completion. 
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Esempio n. 55
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     _cancellationTokenSource.Cancel();
 }
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to:
        /// 1. Another Media app comes into foreground and starts playing music 
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("MyBackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                backgroundTaskStarted.Reset();

                // save state
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, GetCurrentTrackId() == null ? null : GetCurrentTrackId().ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Canceled.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, Enum.GetName(typeof(AppState), foregroundAppState));

                // unsubscribe from list changes
                if (playbackList != null)
                {
                    playbackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
                    playbackList = null;
                }

                // unsubscribe event handlers
                BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground;
                smtc.ButtonPressed -= smtc_ButtonPressed;
                smtc.PropertyChanged -= smtc_PropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion. 
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Esempio n. 57
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     // Maybe do something...
 }
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     _taskDeferral?.Complete();
 }
 private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     m_cancelRequested = true;
     Debug.WriteLine("EdpBackgroundTask " + sender.Task.Name + " Cancel Requested...");
 }
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     Debug.WriteLine("Task cancelled, clean up");
     serviceDeferral?.Complete();
 }