0
votes

I want to use a background task for my UWP app.

The below code, is my back button click event in windows mobile:

private async void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
    {
       var access= await BackgroundExecutionManager.RequestAccessAsync();
        var task = new BackgroundTaskBuilder
        {
            Name="My task",TaskEntryPoint=typeof(backGroundTask.Class1).ToString()
        };
        trigger = new ApplicationTrigger();
        task.SetTrigger(trigger);
        task.Register();
        //var result = await trigger.RequestAsync();
        if (Frame.CanGoBack)
        {
            Frame.GoBack();
            e.Handled = true;
        }
    }


public void Run(IBackgroundTaskInstance taskInstance)
    {
        _deferral = taskInstance.GetDeferral();
        clearData();
        count1 = 0;
        getDownloadedSongs();

        dispatcherTimer1.Tick += DispatcherTimer1_Tick;
        dispatcherTimer1.Interval = new TimeSpan(0, 0, 3);
        dispatcherTimer1.Start();
        _deferral.Complete();



    }
    DispatcherTimer dispatcherTimer1 = new DispatcherTimer();

 private async void DispatcherTimer1_Tick(object sender, object e)
    {

        try
        {
              clearData();




        }
        catch (Exception ex)
        {
        }



    }

But this code is not working, when I click back button. As per expectation background task code should work, but it is not working. What am I doing wrong?

1
This is happening because the application is getting closed before the background task is registered... it is not recommended to register background task on back requested or any other code that takes time. Try registering your background task on some other event before the user actually exists the application.Pratyay
Thanks for replying..Now I am registering this on another button click event ..Still not working..I must be missing somethinguncle_scrooge
Did you declare the background task in the appx manifest? Is 'backgroundTask.Class1' a public activatable WinRT component? Also can you clarify what you really want to accomplish? I am wondering if ExtendedExectuion would be a better approach to your scenario.Stefan Wick MSFT
Yes..I have already declared..Also tried extendedexecution...not working...I just want to try,when i click back button ,instead of suspending app I want to get all images from pictures library and set it as wallpaperuncle_scrooge
In short ..when I click back button(its a one page app),I want to minimize the app in windows mobile(Desktop it is working as expected)..uncle_scrooge

1 Answers

0
votes

Your background task is exiting before the DispatcherTimer gets a chance to ever execute, because you mark the Deferral as complete. You should hold on to the Deferral until all the work in your background task has been completed (or until you receive a TaskCanceled event from the system).