通过DependencyService在UWP中启动后台任务

时间:2016-04-12 14:03:36

标签: c# xamarin win-universal-app

我一直在尝试在后台运行代码。到目前为止,我设法注册了该任务,但Run方法从未执行过。这就是我到目前为止所做的:

BackgroundUWP:

[assembly: Xamarin.Forms.Dependency(typeof(App.UWP.BackgroundUWP))]
namespace App.UWP
{
    class BackgroundUWP : IBackground
    {
        public async void RegisterAndStartTask()
        {
            string taskName = typeof(MyTask).Name;

            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == taskName)
                {
                    task.Value.Unregister(true);
                    break;
                }
            }

            BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
            ApplicationTrigger trigger = new ApplicationTrigger();
            builder.Name = taskName;
            builder.TaskEntryPoint = typeof(MyTask).FullName;
            builder.SetTrigger(trigger);
            BackgroundTaskRegistration t = builder.Register();

            await trigger.RequestAsync();
        }
    }
}

MyTask:

namespace App.UWP
{
    public sealed class MyTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // this method isn't being called
        }
    }
}

清单:

<Extension Category="windows.backgroundTasks" EntryPoint="App.UWP.MyTask">
  <BackgroundTasks>
    <Task Type="systemEvent" />
  </BackgroundTasks>
</Extension>

设置断点时,我的应用达到await trigger.RequestAsync();。在控制台中,我注意到此消息backgroundTaskHost.exe has exited with code 1。我该怎么做才能解决这个问题?

编辑:

可能与this问题有关。我的项目看起来像这样:

  • App(PCL)
  • App.UWP

1 个答案:

答案 0 :(得分:0)

我必须使用实现IBackgroundTask的类创建一个新的Windows运行时组件(通用Windows)项目,并添加对UWP项目的引用。

问题是我在App.UWP项目中有一个类,它不是Windows运行时组件项目。