Exemplo n.º 1
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            controls.ButtonPressed -= SystemMediaTransportControls_ButtonPressed;

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
Exemplo n.º 2
0
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            SaveText(DateTime.Now.Ticks, "Cancel", id, reason);

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
        /// <summary>
        /// The background task did exist, but it has disappeared. Put the foreground back into an initial state. Unfortunately,
        /// any attempts to unregister things on BackgroundMediaPlayer.Current will fail with the RPC error once the background task has been lost.
        /// </summary>
        public void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;
            backgroundAudioTaskStarted.Reset();
            prevButton.IsEnabled = true;
            nextButton.IsEnabled = true;
            AppSettingsHelper.SaveVal(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknown.ToString());
            playButton.Content = "| |";

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Вызывается при отмене фоновой задачи.
        /// </summary>
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            try
            {
                _isTaskRunning = false;
                _isAppRunning  = false;
                _taskRunning.Reset();
                _operationCompleted.Set();

                _controls.ButtonPressed     -= Controls_ButtonPressed;
                _player.CurrentStateChanged -= Player_CurrentStateChanged;
                _manager.TrackChanged       -= Manager_TrackChanged;
                BackgroundMediaPlayer.MessageReceivedFromForeground -= MessageReceivedFromForeground;

                _manager = null;
                _settingsService.Set(TASK_RUNNING, false);
                _settingsService       = null;
                _playerPlaylistService = null;
                _logService            = null;
                _musicCacheService     = null;
                _player = null;

                TileUpdateManager.CreateTileUpdaterForApplication("App").Clear();

                BackgroundMediaPlayer.Shutdown();
            }
            catch (Exception ex)
            {
                _logService?.LogException(ex);
            }

            _deferral.Complete();
        }
Exemplo n.º 5
0
 private void OnTaskCancelled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     // Cancel all serial operations, close port and exit read operations
     _timer.Cancel();
     BackgroundMediaPlayer.Shutdown();
     _deferral.Complete();   // Notify that the operation is completed.
 }
Exemplo n.º 6
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(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;
                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Exemplo n.º 7
0
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            try
            {
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_CURRENT_TRACK, Playlist.CurrentTrackName);
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_POSITION, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_STATE, SharedStrings.BACKGROUND_AUDIO_CANCELLED);
                ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_APP_STATE, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
                backgroundTaskRunning = false;

                if (transportControl != null)
                {
                    transportControl.ButtonPressed   -= transportControl_ButtonPressed;
                    transportControl.PropertyChanged -= transportControl_PropertyChanged;
                }
                Playlist.TrackChanged -= playList_TrackChanged;

                playlistManager.ClearPlaylist();
                playlistManager = null;
                BackgroundMediaPlayer.Shutdown();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("CoffeeBackgroundAudioTask.OnCanceled: " + ex.ToString());
            }
            if (deferral != null)
            {
                deferral.Complete();
                deferral = null;
            }
        }
Exemplo n.º 8
0
        async private void ResetBackgroundAudio()
        {
            BackgroundMediaPlayer.Shutdown();
            await Task.Delay(TimeSpan.FromSeconds(2));

            StartBackgroundAudioTask();
        }
Exemplo n.º 9
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
            {
                if (_queueManager != null)
                {
                    QueueManager.TrackChanged -= playList_TrackChanged;
                    _queueManager              = null;
                }

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

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

            if (_deferral != null)
            {
                _deferral.Complete(); // signals task completion.
                Debug.WriteLine("AudioPlayer Cancel complete...");
            }
        }
Exemplo n.º 10
0
        private void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;
            backgroundAudioTaskStarted.Reset();
            audioPlayer.CanGoPrevious = false;
            audioPlayer.CanGoNext     = false;
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknow.ToString());
            audioPlayer.IsPlaying = true;

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 11
0
        private void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;
            backgroundAudioTaskStarted.Reset();
            //prevButton.IsEnabled = true;
            //nextButton.IsEnabled = true;
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknown.ToString());
            Pause.Icon = new SymbolIcon(Symbol.Pause);

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
        /// <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.BackgroundTaskState, BackgroundTaskState.Canceled.ToString());

                // 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...");
        }
Exemplo n.º 13
0
        /// <summary>
        /// The background task did exist, but it has disappeared. Put the foreground back into an initial state. Unfortunately,
        /// any attempts to unregister things on BackgroundMediaPlayer.Current will fail with the RPC error once the background task has been lost.
        /// </summary>
        private void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;
            backgroundAudioTaskStarted.Reset();
            PreviousButtonIsEnabled = true;
            NextButtonIsEnabled     = true;
            StopButtonVisibility    = Visibility.Collapsed;
            PlayButtonVisibility    = Visibility.Visible;
            PlayButtonIsEnabled     = true;
            RefreshBindings();

            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknown.ToString());

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 14
0
        private void HandleTaskInstanceCanceled(IBackgroundTaskInstance taskInstance, BackgroundTaskCancellationReason reason)
        {
            PlayQueueManager.Current.Disconnect();

            TileUpdateManager.CreateTileUpdaterForApplication("App").Clear();

            Logger.Current.Log(new CallerInfo(), LogLevel.Info, "AudioPlayer Background Task Completed id:{0} reason:{1}", taskInstance.Task.TaskId, reason.ToString());

            ApplicationSettings.PutSettingsValue(ApplicationSettings.IS_BACKGROUND_PROCESS_ACTIVE, false);

            if (ApplicationSettings.GetSettingsValue <bool>(ApplicationSettings.IS_FOREGROUND_PROCESS_ACTIVE, false))
            {
                PlayQueueManager.Current.SendMessageToForeground(PlayQueueConstantBGMessageId.BackgroundEnded);
            }

            backgroundTaskState = BackgroundTaskState.Stopped;

            PlayQueueManager.Current.TrackChanged -= HandlePlayQueueTrackChanged;

            BackgroundMediaPlayer.Current.CurrentStateChanged -= HandleBackgroundMediaPlayerCurrentStateChanged;
            taskInstance.Task.Completed -= HandleTaskInstanceTaskCompleted;
            taskInstance.Canceled       -= HandleTaskInstanceCanceled;

            BackgroundMediaPlayer.Shutdown();

            Logger.Current.Flush();

            backgroundTaskDefferal.Complete();
        }
        /// <summary>
        /// The background task did exist, but it has disappeared. Put the foreground back into an initial state. Unfortunately,
        /// any attempts to unregister things on BackgroundMediaPlayer.Current will fail with the RPC error once the background task has been lost.
        /// </summary>
        private void ResetAfterLostBackground()
        {
            backgroundAudioTaskStarted.Reset();
            BackgroundMediaPlayer.Shutdown();

            try
            {
                BackgroundMediaPlayer.MessageReceivedFromBackground -= BackgroundPlayerMessageReceivedFromBackground;
                BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundPlayerMessageReceivedFromBackground;
            }
            catch (Exception ex)
            {
                if (ex.HResult == RPC_S_SERVER_UNAVAILABLE)
                {
                    telemetry.TrackException(ex, new Dictionary <string, string> {
                        { "Scenario", "ResetPlayerServerUnavailable" }
                    });
                    throw new Exception("Failed to get a MediaPlayer instance.");
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 16
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...");
        }
Exemplo n.º 17
0
        private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            SaveText(DateTime.Now.Ticks, "Complete", id, sender.Name);

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
Exemplo n.º 18
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;

            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait;

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                try
                {
                    if (BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState == MediaPlaybackState.Paused | BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState == MediaPlaybackState.None)
                    {
                        (Radio.Icon as BitmapIcon).UriSource = uriMute;
                    }
                    if (BackgroundMediaPlayer.Current.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
                    {
                        (Radio.Icon as BitmapIcon).UriSource = uriSound;
                    }
                } catch (Exception)
                {
                    (Radio.Icon as BitmapIcon).UriSource = uriMute;
                    BackgroundMediaPlayer.Shutdown();
                }
            });

            BackgroundMediaPlayer.Current.CurrentStateChanged += radioPlayer_CurrentStateChanged;
        }
Exemplo n.º 19
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)
        {
            // Shutdown media pipeline
            try { BackgroundMediaPlayer.Shutdown(); } catch { }

            // Signals task completition
            deferral.Complete();
        }
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     BackgroundMediaPlayer.Shutdown();
     if (deferral != null)
     {
         deferral.Complete();
     }
 }
Exemplo n.º 21
0
        private void Cancel()
        {
            ringer?.Dispose();
            musicPlayer?.Dispose();

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
 public static void Interrupt()
 {
     if (_isInitialized)
     {
         BackgroundMediaPlayer.Shutdown();
         _isInitialized = false;
     }
 }
Exemplo n.º 23
0
        public async Task ShutdownPlayerAsync()
        {
            RemoveMediaPlayerEventHandlers();
            BackgroundMediaPlayer.Shutdown();
            AppSettingsHelper.Write(PlayerConstants.CurrentTrack, null);
            await Task.Delay(1000);

            _isShutdown = true;
            RaiseEvent(Shutdown);
        }
Exemplo n.º 24
0
        private void Taskcompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
        {
            FolderMusicUwpLib.SaveTextClass.SaveText("Completed");

            LibraryLib.CurrentSong.Current.Save();
            Library.Current.SaveAsync();

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
Exemplo n.º 25
0
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            FolderMusicUwpLib.SaveTextClass.SaveText("Canceled");

            LibraryLib.CurrentSong.Current.Save();
            Library.Current.SaveAsync();

            BackgroundMediaPlayer.Shutdown();
            deferral.Complete();
        }
        public void Shutdown()
        {
            Debug.WriteLine("MediaPlayerHandle.Shutdown()");

            _subscriptionHandle.Unsubscribe();

            Close();

            BackgroundMediaPlayer.Shutdown();
        }
Exemplo n.º 27
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 TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            try
            {
                systemmediatransportcontrol.ButtonPressed -= Systemmediatransportcontrol_ButtonPressed;
                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch { }

            deferral.Complete(); // signals task completion.
        }
Exemplo n.º 28
0
        private void Current_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            BackgroundMediaPlayer.Shutdown();
            _isMyBackgroundTaskRunning = false;

            // save state
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, 0);
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Canceled.ToString());
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, Enum.GetName(typeof(AppState), AppState.Unknown));
        }
Exemplo n.º 29
0
        //TODO: 完善后台获取失败的方法
        private void ResetAfterLostBackground()
        {
            BackgroundMediaPlayer.Shutdown();
            _isBackgroundTaskRunning = false;
            //prevButton.IsEnabled = true;
            //nextButton.IsEnabled = true;
            SettingsService.Playback.Write(nameof(BackgroundTaskState), BackgroundTaskState.Unknown.ToString());
            //playButton.Content = "||";

            AddMessageHandler();
        }
Exemplo n.º 30
0
        public void FullShutdown()
        {
            var player = SafeMediaPlayer;

            if (player == null)
            {
                return;
            }

            RemoveMediaPlayerEventHandlers(player);
            BackgroundMediaPlayer.Shutdown();
            App.Locator.AppSettingsHelper.Write(PlayerConstants.CurrentTrack, null);
        }