/// <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;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("MyBackgroundAudioTask Cancel complete...");
        }
Exemple #2
0
        public void SetDB()
        {
            DatabaseManager.CreateDatabase();
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.DBVersion, 3);
            int i;

            i = DatabaseManager.InsertSmartPlaylist2("Ostatnio dodane", 50, SPUtility.SortBy.MostRecentlyAdded);
            DatabaseManager.InsertSmartPlaylistEntry2(i, SPUtility.Item.DateAdded, SPUtility.Comparison.IsGreater, DateTime.Now.Subtract(TimeSpan.FromDays(14)).Ticks.ToString());
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.OstatnioDodane, i);
            i = DatabaseManager.InsertSmartPlaylist2("Ostatnio odtwarzane", 50, SPUtility.SortBy.MostRecentlyPlayed);
            DatabaseManager.InsertSmartPlaylistEntry2(i, SPUtility.Item.LastPlayed, SPUtility.Comparison.IsGreater, DateTime.MinValue.Ticks.ToString());
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.OstatnioOdtwarzane, i);
            i = DatabaseManager.InsertSmartPlaylist2("Najczęściej odtwarzane", 50, SPUtility.SortBy.MostOftenPlayed);
            DatabaseManager.InsertSmartPlaylistEntry2(i, SPUtility.Item.PlayCount, SPUtility.Comparison.IsGreater, "0");
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.NajczesciejOdtwarzane, i);
            i = DatabaseManager.InsertSmartPlaylist2("Najlepiej oceniane", 50, SPUtility.SortBy.HighestRating);
            DatabaseManager.InsertSmartPlaylistEntry2(i, SPUtility.Item.Rating, SPUtility.Comparison.IsGreater, "3");
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.NajlepiejOceniane, i);
            i = DatabaseManager.InsertSmartPlaylist2("Najrzadziej odtwarzane", 50, SPUtility.SortBy.LeastOftenPlayed);
            DatabaseManager.InsertSmartPlaylistEntry2(i, SPUtility.Item.PlayCount, SPUtility.Comparison.IsGreater, "-1");
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.NajrzadziejOdtwarzane, i);
            i = DatabaseManager.InsertSmartPlaylist2("Najgorzej oceniane", 50, SPUtility.SortBy.LowestRating);
            DatabaseManager.InsertSmartPlaylistEntry2(i, SPUtility.Item.Rating, SPUtility.Comparison.IsLess, "4");
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.NajgorzejOceniane, i);
        }
        /// <summary>
        /// Raised when playlist changes to a new track
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args)
        {
            // Get the new item
            var item = args.NewItem;

            Debug.WriteLine("PlaybackList_CurrentItemChanged: " + (item == null ? "null" : GetTrackId(item).ToString()));

            // Update the system view
            UpdateUVCOnNewTrack(item);

            // Get the current track
            Uri currentTrackId = null;

            if (item != null)
            {
                currentTrackId = item.Source.CustomProperties[TrackIdKey] as Uri;
            }

            // Notify foreground of change or persist for later
            if (foregroundAppState == AppState.Active)
            {
                MessageService.SendMessageToForeground(new TrackChangedMessage(currentTrackId));
            }
            else
            {
                ApplicationSettingsHelper.SaveSettingsValue(TrackIdKey, currentTrackId == null ? null : currentTrackId.ToString());
            }
        }
Exemple #4
0
        public async Task SetMobileSession()
        {
            Dictionary <string, string> data = new Dictionary <string, string>();

            data.Add("username", Username);
            data.Add("password", Password);
            data.Add("method", "auth.getMobileSession");
            data.Add("api_key", ApiKey);
            string signature = GetSignature(data);

            data.Add("api_sig", signature);

            string response = await SendMessage(data, true);

            if (response.Contains("<lfm status=\"ok\">"))
            {
                int i1 = response.IndexOf("<key>") + "<key>".Length;
                int i2 = response.IndexOf("</key>");
                SessionKey = response.Substring(i1, i2 - i1);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmSessionKey, SessionKey);
            }
            else
            {
                ParseError(response);
            }
        }
Exemple #5
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;
            }
        }
Exemple #6
0
        void ForegroundApp_Resuming(object sender, object e)
        {
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, AppState.Active.ToString());

            // Verify the task is running
            if (IsMyBackgroundTaskRunning)
            {
                // If yes, it's safe to reconnect to media play handlers
                AddMediaPlayerEventHandlers();

                // Send message to background task that app is resumed so it can start sending notifications again
                MessageService.SendMessageToBackground(new AppResumedMessage());

                UpdateTransportControls(CurrentPlayer.CurrentState);

                var trackId = GetCurrentTrackIdAfterAppResume();
                NowPlayingTitle.Text = trackId == null ? string.Empty : songs.Single(s => s.MediaUri == trackId).Title;
                //txtCurrentState.Text = CurrentPlayer.CurrentState.ToString();
            }
            else
            {
                Pause.Icon           = new SymbolIcon(Symbol.Play); // Change to play button
                NowPlayingTitle.Text = string.Empty;
                //txtCurrentState.Text = "Background Task Not Running";
            }
        }
Exemple #7
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)
        {
            try
            {
                backgroundTaskStarted.Reset();

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

                if (playbackList != null)
                {
                    playbackList.CurrentItemChanged -= OnCurrentItemChanged;
                    playbackList = null;
                }

                BackgroundMediaPlayer.MessageReceivedFromForeground -= OnMessageFromForegroundReceived;
                smtc.ButtonPressed   -= OnSmtcButtonPressed;
                smtc.PropertyChanged -= OnSmtcPropertyChanged;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete();
        }
Exemple #8
0
        public async void Pin(GenreItem genre)
        {
            int    id     = ApplicationSettingsHelper.ReadTileIdValue() + 1;
            string tileId = AppConstants.TileId + id.ToString();

            ApplicationSettingsHelper.SaveTileIdValue(id);

            string displayName             = "Next Player";
            string tileActivationArguments = ParamConvert.ToString(new string[] { "genre", genre.GenreParam });
            Uri    square150x150Logo       = new Uri("ms-appx:///Assets/AppImages/Logo/Logo.png");

            SecondaryTile secondaryTile = new SecondaryTile(tileId,
                                                            displayName,
                                                            tileActivationArguments,
                                                            square150x150Logo,
                                                            TileSize.Wide310x150);

            secondaryTile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///Assets/AppImages/WideLogo/WideLogo.png");
            secondaryTile.VisualElements.Square71x71Logo = new Uri("ms-appx:///Assets/AppImages/Square71x71Logo/Square71x71LogoTr.png");


            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileId, tileId);
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileName, genre.Genre);
            ResourceLoader loader = new ResourceLoader();

            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileType, loader.GetString("Genre"));

            App.OnNewTilePinned = UpdateNewSecondaryTile;

            await secondaryTile.RequestCreateAsync();
        }
Exemple #9
0
        private void Play(MusicItem track)
        {
            var uri       = track.Source;
            var uriString = uri.ToString();

            Debug.WriteLine($"Playing: {uriString}");

            // Start the background task if it wasn't running
            if (!IsMyBackgroundTaskRunning || MediaPlayerState.Closed == CurrentPlayer.CurrentState)
            {
                // First update the persisted start track
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, uriString);
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, new TimeSpan().ToString());

                // Start task
                StartBackgroundAudioTask();
            }
            else
            {
                // Switch to the selected track
                MessageService.SendMessageToBackground(new TrackChangedMessage(uri));
            }

            if (MediaPlayerState.Paused == CurrentPlayer.CurrentState)
            {
                CurrentPlayer.Play();
            }
        }
        /// <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...");
        }
Exemple #11
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;
                }
            }
        }
Exemple #12
0
 void Initialize()
 {
     if (ApplicationSettingsHelper.ReadSettingsValue("ContinueVideoPlaybackInBackground") == null)
     {
         ApplicationSettingsHelper.SaveSettingsValue("ContinueVideoPlaybackInBackground", true);
     }
 }
        public async Task UpdateAppTile(bool isTransparent)
        {
            XmlDocument tileXml             = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Image);
            XmlDocument wideTile            = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image);
            var         tileImageAttributes = tileXml.GetElementsByTagName("image");
            var         wideImageAttributes = wideTile.GetElementsByTagName("image");

            if (isTransparent)
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileAppTransparent, "yes");
                tileImageAttributes[0].Attributes.GetNamedItem("src").NodeValue = "ms-appx:///Assets/AppImages/Logo/LogoTr.png";
                wideImageAttributes[0].Attributes.GetNamedItem("src").NodeValue = "ms-appx:///Assets/AppImages/WideLogo/WideLogoTr.png";
            }
            else
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileAppTransparent, "no");
                tileImageAttributes[0].Attributes.GetNamedItem("src").NodeValue = "ms-appx:///Assets/AppImages/Logo/Logo.png";
                wideImageAttributes[0].Attributes.GetNamedItem("src").NodeValue = "ms-appx:///Assets/AppImages/WideLogo/WideLogo.png";
            }

            IXmlNode node = tileXml.ImportNode(wideTile.GetElementsByTagName("binding").Item(0), true);

            tileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);

            TileNotification tileNotification = new TileNotification(tileXml);

            TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
        }
        public async void Initialize(object mediaElement)
        {
            ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.AppState, BackgroundAudioConstants.ForegroundAppActive);

            AddMediaPlayerEventHandlers();

            await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                dispatchTimer = new DispatcherTimer()
                {
                    Interval = TimeSpan.FromSeconds(1),
                };
                dispatchTimer.Tick += dispatchTimer_Tick;
            });

            if (Instance.CurrentState == MediaPlayerState.Playing)
            {
                if (!dispatchTimer.IsEnabled)
                {
                    await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        Locator.MediaPlaybackViewModel.IsPlaying = true;
                        Instance_CurrentStateChanged(null, new RoutedEventArgs());
                    });
                }
            }
            if (Instance != null && PlayerInstanceReady.Task?.Status != TaskStatus.RanToCompletion)
            {
                PlayerInstanceReady.SetResult(true);
            }
        }
Exemple #15
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                myMusic = await deserialize();
            }
            catch { }
            if (myMusic.albumList == null || myMusic.songList == null)
            {
                await GetMusic();
            }
            ProgressbarMain.ShowPaused = true;
            MainFrame.Navigate(typeof(AlbumView), myMusic);
            BackgroundFrame.Navigate(typeof(NowPlaying));


            var MediaElementObject = new MediaElement();

            Application.Current.Suspending += ForegroundApp_Suspending;
            Application.Current.Resuming   += ForegroundApp_Resuming;
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, AppState.Active.ToString());

            NowPlatingCover.Source = new BitmapImage(new Uri("ms-appx:///Assets/main.png"));
            NowPlayingTitle.Text   = "MusicFlow";
            NowPlayingArtist.Text  = "For Windows 10";
        }
        private async void LFMLoginButton_Click(object sender, RoutedEventArgs e)
        {
            LFMLoginButton.IsEnabled = false;
            bool isLoggedIn = await LastFmManager.Current.Login(LFMLogin.Text, LFMPassword.Password);

            LFMLoginButton.IsEnabled = true;
            if (isLoggedIn)
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmLogin, LFMLogin.Text);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmPassword, LFMPassword.Password);
                LFMLoginButton.Visibility  = Visibility.Collapsed;
                LFMLogoutButton.Visibility = Visibility.Visible;
                LFMLoginError.Visibility   = Visibility.Collapsed;

                TBLogin.Visibility          = Visibility.Collapsed;
                TBPassword.Visibility       = Visibility.Collapsed;
                TBYouAreLoggedIn.Visibility = Visibility.Visible;

                LFMPassword.Visibility = Visibility.Collapsed;
                LFMLogin.Visibility    = Visibility.Collapsed;

                LFMPassword.Password = "";
                TrackEvent("LastFm Log in");
            }
            else
            {
                LFMPassword.Password     = "";
                LFMLoginError.Visibility = Visibility.Visible;
            }
        }
        private void MinLove_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = (int)((ComboBox)sender).SelectedIndex;

            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmLove, i + 1);
            App.LastFmLove = i + 1;
        }
        public async void PinPlaylist(PlaylistItem p)
        {
            //string tileId = p.IsSmart ? AppConstants.TileId + p.Id + "smart": AppConstants.TileId + p.Id + "plain";
            int    id     = ApplicationSettingsHelper.ReadTileIdValue() + 1;
            string tileId = AppConstants.TileId + id.ToString();

            ApplicationSettingsHelper.SaveTileIdValue(id);

            if (!SecondaryTile.Exists(tileId))
            {
                string displayName             = "Next Player";
                string tileActivationArguments = ParamConvert.ToString(new string[] { "playlist", p.Id.ToString(), p.IsSmart.ToString() });
                Uri    square150x150Logo       = new Uri("ms-appx:///Assets/AppImages/Logo/Logo.png");

                SecondaryTile secondaryTile = new SecondaryTile(tileId,
                                                                displayName,
                                                                tileActivationArguments,
                                                                square150x150Logo,
                                                                TileSize.Wide310x150);
                secondaryTile.VisualElements.Wide310x150Logo = new Uri("ms-appx:///Assets/AppImages/WideLogo/WideLogo.png");
                secondaryTile.VisualElements.Square71x71Logo = new Uri("ms-appx:///Assets/AppImages/Square71x71Logo/Square71x71LogoTr.png");


                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileId, tileId);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileName, p.Name);
                ResourceLoader loader = new ResourceLoader();
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileType, loader.GetString("Playlist"));

                App.OnNewTilePinned = UpdateNewSecondaryTile;

                await secondaryTile.RequestCreateAsync();
            }
        }
Exemple #19
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;
                }
            }
        }
Exemple #20
0
        private void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
        {
            foreach (string key in e.Data.Keys)
            {
                switch (key.ToLower())
                {
                case SharedStrings.BACKGROUND_AUDIO_APP_SUSPENDED:
                    foregroundAppState = ForegroundAppStatus.Suspended;
                    ApplicationSettingsHelper.SaveSettingsValue(SharedStrings.BACKGROUND_AUDIO_CURRENT_TRACK, Playlist.CurrentTrackName);
                    break;

                case SharedStrings.BACKGROUND_AUDIO_APP_RESUMED:
                    foregroundAppState = ForegroundAppStatus.Active;
                    break;

                case SharedStrings.BACKGROUND_AUDIO_START_PLAYBACK:
                    StartPlayback();
                    break;

                case SharedStrings.BACKGROUND_AUDIO_SKIP_NEXT:
                    SkipToNext();
                    break;

                case SharedStrings.BACKGROUND_AUDIO_SKIP_PREVIOUS:
                    SkipToPrevious();
                    break;
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// Sends message to background informing app has resumed
        /// Subscribe to MediaPlayer events
        /// </summary>
        void ForegroundApp_Resuming(object sender, object e)
        {
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, AppState.Active.ToString());

            // Verify the task is running
            if (IsMyBackgroundTaskRunning)
            {
                // If yes, it's safe to reconnect to media play handlers
                AddMediaPlayerEventHandlers();

                // Send message to background task that app is resumed so it can start sending notifications again
                MessageService.SendMessageToBackground(new AppResumedMessage());

                UpdateTransportControls(CurrentPlayer.CurrentState);

                int trackId = GetCurrentTrackIdAfterAppResume();

                CurrentTrack = trackId == 0 ? null : TrackQueue.Single(s => s.InternalID == trackId);
            }
            else
            {
                StopButtonVisibility = Visibility.Collapsed;
                PlayButtonVisibility = Visibility.Visible;
                PlayButtonIsEnabled  = true;
            }

            RefreshBindings();
        }
Exemple #22
0
        public void Set(string passcode)
        {
            Password = Enc(passcode);

            MainPage.Current.LockControl.Visibility = Visibility.Visible;
            ApplicationSettingsHelper.SaveSettingsValue("MINISTAVERSION", Password);
        }
Exemple #23
0
        private void ListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var clickedSong = (Song)e.ClickedItem;

            mainpage.Songs.Clear();
            var song1 = new SongModel();

            song1.Title       = clickedSong.Title;
            song1.MediaUri    = new Uri(clickedSong.SongFile);
            song1.AlbumArtUri = new Uri(clickedSong.AlbumCover);
            song1.Artist      = clickedSong.Artist;
            mainpage.Songs.Add(song1);
            var s1list = new List <SongModel>();

            s1list.Add(song1);
            MessageService.SendMessageToBackground(new UpdatePlaylistMessage(s1list));
            if (!mainpage.IsMyBackgroundTaskRunning || MediaPlayerState.Closed == mainpage.CurrentPlayer.CurrentState)
            {
                // First update the persisted start track
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, song1.MediaUri.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, new TimeSpan().ToString());

                // Start task
                mainpage.StartBackgroundAudioTask();
            }
            MessageService.SendMessageToBackground(new StartPlaybackMessage());
        }
Exemple #24
0
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            Debug.WriteLine($"{nameof(BackgroundAudioTask)} {sender.Task.TaskId} Cancel Requested...");
            try
            {
                backgroundTaskStarted.Reset();

                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, GetCurrentTrackId()?.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Canceled);
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, foregroundAppState);

                if (playbackList != null)
                {
                    playbackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
                    playbackList = null;
                }

                BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground;
                smtc.ButtonPressed   -= smtc_ButtonPressed;
                smtc.PropertyChanged -= smtc_PropertyChanged;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
            deferral.Complete();
            Debug.WriteLine(nameof(BackgroundAudioTask) + " Cancel complete...");
        }
Exemple #25
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;
                }
            }
        }
Exemple #26
0
 public void OnDeactivated()
 {
     if (isMyBackgroundTaskRunning)
     {
         RemoveMediaPlayerEventHandlers();
         ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());
     }
 }
 public override Task OnNavigatedFromAsync(IDictionary <string, object> pageState, bool suspending)
 {
     if (isMyBackgroundTaskRunning)
     {
         ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());
     }
     return(base.OnNavigatedFromAsync(pageState, suspending));
 }
Exemple #28
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            playlistView.DoubleTapped += PlaylistView_DoubleTapped;

            Application.Current.Suspending += ForegroundApp_Suspending;
            Application.Current.Resuming   += ForegroundApp_Resuming;
            ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, AppState.Active.ToString());
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            if (isMyBackgroundTaskRunning)
            {
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());
            }

            base.OnNavigatedFrom(e);
        }
Exemple #30
0
        private void OnEnteredBackground(object sender, EnteredBackgroundEventArgs enteredBackgroundEventArgs)
        {
            ApplicationSettingsHelper.SaveSettingsValue("AppBackgrounded", true);

            if (Locator.PlaybackService.PlayingType == PlayingType.Video && Locator.PlaybackService.IsPlaying)
            {
                Locator.PlaybackService.Pause();
            }
        }