Windows Phone 8.1 Background task: crashes when de

2019-08-04 19:29发布

问题:

I'm trying to develop I background task, that simply updates a badge on a tile in Windows Phone.

I think I implemented everything correctly, but when I fire of the back ground task in debug mode, the app simply crashes.

Here is my code:

The Background class

 public sealed class TileBadgeUpdate : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
        updateBadge();
        deferral.Complete();
    }

    private void updateBadge()
    {
        var badgeXML = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
        var badge = badgeXML.SelectSingleNode("/badge") as XmlElement;
        badge.SetAttribute("value", "20");
        var badgeNotification = new BadgeNotification(badgeXML);
        BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badgeNotification);
    }

I register the background task in the "OnNavigatedTo" of one of my pages. I can successfully debug this code:

        foreach (var task in BackgroundTaskRegistration.AllTasks)
        {
            task.Value.Unregister(true);
        }

        var builder = new BackgroundTaskBuilder();
        builder.Name = "NewBGTask";
        builder.TaskEntryPoint = "POCTimesheetEntry.TileBadgeUpdate";
        builder.SetTrigger(new TimeTrigger(15, false));
        var ret = builder.Register();

In the AppxManifest

I have registered the background task:

What am I doing wrong?

Thanks in advance

Matthew

回答1:

  1. Check if you have created BackgroundTask (Windows Run Time Component) project separately. IT IS MUST WHEN YOU CREATE BACKGROUND TASK IN WINDOWS PHONE 8.1 APP, YOU CREATE SEPARATE PROJECT AS WINDOWS COMPONENT

  2. See if you have forgot to add reference of Backgroud Task Project to your Project.

In my case I forgot to add reference of background task project hence geofencetask.Completed was not getting called.