locked
Manually starting BackgroundTask on Windows Phone 8.1

    Question

  • When running an application that has a BackgroundAudioTask everything works fine. When I now start another application that uses a BackgroundAudioTask it will cancel the BackgroundAudioTask of my application. When I go back to my application I want to re-register my BackgroundAudioTask so that it will behave as it did originally.

    In Package.appxmanifest I have the following:

    <Extensions>
        <Extension Category="windows.backgroundTasks" EntryPoint="WindowsPhoneBackgroundAudioTask.BackgroundAudioTask">
          <BackgroundTasks>
            <Task Type="audio" />
          </BackgroundTasks>
        </Extension>
      </Extensions>

    When I first run the application the Run method will be called and I add a Deferral to the task to make sure it is kept alive even when I close my application:

    public void Run(IBackgroundTaskInstance taskInstance)
    {
        setupDeferral = taskInstance.GetDeferral();
    } 

    When I start the music player from another application my BackgroundAudioTask Cancelled event is called (If I don't do setupDeferral.Complete() here my application will crash):

    private void Task_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
        setupDeferral.Complete();
    }

    When I open my application how do I recreate my BackgroundAudioTask. The problem is the Runmethod is never called again so I can't setup the Deferral again. Music will now play fine but as soon as I navigate away from the application the music will stop.

    I tried manually re-registering the task in App.xaml.cs in the App_Resuming event with this code:

    var taskBuilder = new BackgroundTaskBuilder();
    taskBuilder.Name = "BackgroundAudioTask";
    taskBuilder.TaskEntryPoint = typeof(WindowsPhoneBackgroundAudioTask.BackgroundAudioTask).FullName;
    BackgroundTaskRegistration task = taskBuilder.Register();

    The above code will throw and Invalid Argument Exception because it does not have a Trigger setup. I don't want it to have a trigger. I just want to start the background task immediately.

    So in short. I need to recreate the BackgroundAudioTask somehow so that it calls the Run method again so that it can get a Deferral setup.

    Tuesday, December 23, 2014 7:04 AM

Answers