2
votes

Hello as part of an app that plays relaxing music in the background using the BackgroundMediaPlayer, I would like to implement a way of turning off the music after a set time..

What I was thinking was to have a TimerPicker for the user to pick when the music should stop and then add Timer as a supported task type to my MusicBackgroundTask under the Declarations in the appxmanifest.

Then properly in some way use a ThreadPoolTimer in my MusicBackgroundTask Windows Runtime Component to stop the music when it ticks, but I really cant find anywhere online that explains how to make timers in a background task work.

So if anyone have a good link that explains or better some working code it would be a great help, thank you very much..

1

1 Answers

1
votes

Here is an MSDN sample that shows an IBackgroundTask implementation using a ThreadPoolTimer (see SampleBackgroundTask.cs): http://code.msdn.microsoft.com/windowsapps/Background-Task-Sample-9209ade9/sourcecode?fileId=43572&pathId=498327315

One potential reason for this not working is if you did not keep a reference to the object returned from IBackgroundTaskInstance.GetDeferral() which would cause your background task to complete prematurely after IBackgroundTask.Run returns. The sample linked above does this and I believe this is also required for the BackgroundMediaPlayer Audio task to continue playing music so I would be surprised if you didn't already have this.

Finally, the "Timer" task type in your MusicBackgroundTask declaration in the appxmanifest file will have no impact for your usage of ThreadPoolTimer. The "Timer" task type is to allow an IBackgroundTask entrypoint to be triggered by TimeTrigger and MaintenanceTrigger triggers.