/// <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(); }