public void Run(IBackgroundTaskInstance taskInstance)
{
Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting...");
// Initialize SystemMediaTransportControls (SMTC) for integration with
// the Universal Volume Control (UVC).
//
// The UI for the UVC must update even when the foreground process has been terminated
// and therefore the SMTC is configured and updated from the background task.
smtc = BackgroundMediaPlayer.Current.SystemMediaTransportControls;
smtc.ButtonPressed += smtc_ButtonPressed;
smtc.PropertyChanged += smtc_PropertyChanged;
smtc.IsEnabled = true;
smtc.IsPauseEnabled = true;
smtc.IsPlayEnabled = true;
smtc.IsNextEnabled = true;
smtc.IsPreviousEnabled = true;
// Read persisted state of foreground app
var value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.AppState);
if (value == null)
foregroundAppState = AppState.Unknown;
else
foregroundAppState = EnumHelper.Parse<AppState>(value.ToString());
// Add handlers for MediaPlayer
BackgroundMediaPlayer.Current.CurrentStateChanged += Current_CurrentStateChanged;
// Initialize message channel
BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
// Send information to foreground that background task has been started if app is active
if (foregroundAppState != AppState.Suspended)
MessageService.SendMessageToForeground(new BackgroundAudioTaskStartedMessage());
ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString());
deferral = taskInstance.GetDeferral(); // This must be retrieved prior to subscribing to events below which use it
// Mark the background task as started to unblock SMTC Play operation (see related WaitOne on this signal)
backgroundTaskStarted.Set();
// Associate a cancellation and completed handlers with the background task.
taskInstance.Task.Completed += TaskCompleted;
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled); // event may raise immediately before continung thread excecution so must be at the end
}