2016-04-23 122 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事件或状态保存事件中的音乐。