2016-04-23 200 views
2

我爲Windows Phone 8.1設計了一款音樂播放器。當我點擊播放按鈕前臺應用程序發送到背景音頻類的消息。背景音頻類播放我的音樂。一切都好。但我有一個問題。當我關閉我的應用程序(按下後退按鈕並向下滑動)返回地面音樂仍在播放。我如何關閉它?謝謝。Windows Phone 8.1後臺任務不停止?

public void Run(IBackgroundTaskInstance taskInstance) 
    { 
     Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting..."); 
     // Initialize SMTC object to talk with UVC. 
     //Note that, this is intended to run after app is paused and 
     //hence all the logic must be written to run in background process 
     systemmediatransportcontrol = SystemMediaTransportControls.GetForCurrentView(); 
     systemmediatransportcontrol.ButtonPressed += systemmediatransportcontrol_ButtonPressed; 
     systemmediatransportcontrol.PropertyChanged += systemmediatransportcontrol_PropertyChanged; 
     systemmediatransportcontrol.IsEnabled = true; 
     systemmediatransportcontrol.IsPauseEnabled = true; 
     systemmediatransportcontrol.IsPlayEnabled = true; 
     systemmediatransportcontrol.IsNextEnabled = true; 
     systemmediatransportcontrol.IsPreviousEnabled = true; 

     // Associate a cancellation and completed handlers with the background task. 
     taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); 
     taskInstance.Task.Completed += Taskcompleted; 

     var value = ApplicationSettingsHelper.ReadResetSettingsValue(Constants.AppState); 
     if (value == null) 
      foregroundAppState = ForegroundAppStatus.Unknown; 
     else 
      foregroundAppState = (ForegroundAppStatus)Enum.Parse(typeof(ForegroundAppStatus), value.ToString()); 

     //Add handlers for MediaPlayer 
     BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged; 

     //Add handlers for playlist trackchanged 
     Playlist.TrackChanged += playList_TrackChanged; 

     //Initialize message channel 
     BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground; 

     //Send information to foreground that background task has been started if app is active 
     if (foregroundAppState != ForegroundAppStatus.Suspended) 
     { 
      ValueSet message = new ValueSet(); 
      message.Add(Constants.BackgroundTaskStarted, ""); 
      BackgroundMediaPlayer.SendMessageToForeground(message); 
     } 
     BackgroundTaskStarted.Set(); 
     backgroundtaskrunning = true; 

     ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskRunning); 
     deferral = taskInstance.GetDeferral();   
    } 

回答

0

This article描述了Windows應用商店應用的應用生命週期。

如果你看一下第一個數字,你可以看到,只有3個相關的應用程序生命週期事件:

激活 - 凸起,當程序首先啓動 暫停 - 程序暫停時觸發(即用戶返回到開始屏幕或其他應用程序) 恢復 - 當程序從掛起狀態喚醒時觸發。 第四次轉換 - 即「未運行」狀態 - 沒有此類通知事件。原因是:你不知道應用何時完全關閉。你也不應該 - 微軟希望你在從「正在運行」到「已暫停」的轉變中執行所有狀態保存邏輯。這樣,他們可以在他們認爲必要時釋放資源。

即使用戶強制終止程序(通過右鍵單擊它並從任務菜單中選擇「關閉」),您將在程序終止前正好進入「暫停」狀態10秒鐘。所以你可以放心,你的狀態保存邏輯將始終執行。

因此,您可以關閉App Suspending事件或狀態保存事件中的音樂。