C# Windows phone应用程序8.1-未启动后台任务

C# Windows phone应用程序8.1-未启动后台任务,c#,windows-runtime,windows-phone-8.1,background-task,C#,Windows Runtime,Windows Phone 8.1,Background Task,我的windows phone 8.1应用程序中的计时器后台任务仅在应用程序从visual studio以调试模式运行时启动。但是,如果我在没有调试的情况下启动debug二进制文件,它就不能工作,15分钟后,几个小时后都不行。我在windows phone 8.1 emulator和诺基亚lumia 920上对它进行了测试,结果是一样的:在调试会话中它可以工作(由系统启动,我可以从调试位置工具栏手动启动),但当手动启动应用程序时,什么都没有发生 我也有windows应用商店应用程序,时间背景任务

我的windows phone 8.1应用程序中的计时器后台任务仅在应用程序从visual studio以调试模式运行时启动。但是,如果我在没有调试的情况下启动debug二进制文件,它就不能工作,15分钟后,几个小时后都不行。我在windows phone 8.1 emulator和诺基亚lumia 920上对它进行了测试,结果是一样的:在调试会话中它可以工作(由系统启动,我可以从调试位置工具栏手动启动),但当手动启动应用程序时,什么都没有发生

我也有windows应用商店应用程序,时间背景任务在其中运行得很好

要使用后台任务,我执行了以下操作:

  • 在我的wp8.1项目清单中,我添加了:

    <Extension Category="windows.backgroundTasks" EntryPoint="data.TimerHandler">
            <BackgroundTasks>
                    <Task Type="timer" />
            </BackgroundTasks>
    </Extension>
    
  • 创建winrt组件项目,将其默认名称空间设置为“data”(与我在主应用程序中用于MyTimerManager类的名称空间相同) 添加了类TimerHandler:

    namespace data
    {
    public sealed class  TimerHandler : IBackgroundTask
    {
        BackgroundTaskDeferral deferral = null;
    
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();
            await BackgroundExecutionManager.RequestAccessAsync();
            await backgroundTimerCallAsync();
            deferral.Complete();
        }
        public static async Task backgroundTimerCallAsync()
        {
            NotificationSender ns = new NotificationSender(false, null, null);
            ns.sendNotification("Timer task msg");//my code which sends notification
        }
    }
    }
    
  • 在我的wp8.1项目中添加了对winrt组件项目的引用

  • 使用相同的名称空间非常重要:在我的Windows Store 8.1应用程序中,直到我意识到这一点,才启动后台任务。在MSFT文档中没有一个字

    每次启动应用程序时,我都会调用setupAlarm(),并在日志中看到任务的名称(一切正常)。但那时什么也没发生。
    如果我手动启动此任务(从Lifecircle事件控件),我会看到我的通知。我记得一个月前写这段代码时,我看到了通知。我已经用msft文档检查了一切,但一切似乎都很好。我还应该做些什么来启动任务?

    在一些示例中,我发现您应该在注册任务之前调用RequestAccessAsync!这就成功了

    之前,这意味着您必须等到RequestAccessAsync完成,我必须在同步代码中调用它,所以我这样做:

        BackgroundExecutionManager.RequestAccessAsync.AsTask().ContinueWith(
            (t) => registerMyTasks()).ConfigureAwait(false);
    

    在一些示例中,我发现您应该在注册任务之前调用RequestAccessAsync!这就成功了

    之前,这意味着您必须等到RequestAccessAsync完成,我必须在同步代码中调用它,所以我这样做:

        BackgroundExecutionManager.RequestAccessAsync.AsTask().ContinueWith(
            (t) => registerMyTasks()).ConfigureAwait(false);