为了在带有Windows 10 IOT Core的无头Raspberry Pi 2上使用UWP应用程序,我们可以使用后台应用程序模板,它基本上创建了一个新的UWP应用程序,它只在启动时执行一个后台任务:
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundApplication1.StartupTask">
<BackgroundTasks>
<iot:Task Type="startup" />
</BackgroundTasks>
</Extension>
</Extensions>为了使应用程序继续运行,我们可以使用以下启动代码:
public void Run( IBackgroundTaskInstance taskInstance )
{
BackgroundTaskDeferral Deferral = taskInstance.GetDeferral();
//Execute arbitrary code here.
}通过这种方式,应用程序将继续运行,并且操作系统不会在IOT世界中的任何超时之后关闭应用程序。
目前为止一切都很好。
但是:当设备关闭时,我希望能够正确地关闭后台应用程序(或者要求应用程序“轻轻”关闭)。
在“正常”UWP应用程序中,您可以订阅OnSuspending事件。
在这种背景情况下,我如何得到关于即将关闭/关闭的通知?
我们非常感谢你的帮助。
提前感谢!
-Simon
发布于 2015-06-25 03:22:34
你需要处理取消的事件。如果设备被正确关闭,后台任务将被取消。如果未注册,Windows也将取消任务。
BackgroundTaskDeferral _defferal;
public void Run(IBackgroundTaskInstance taskInstance)
{
_defferal = taskInstance.GetDeferral();
taskInstance.Canceled += TaskInstance_Canceled;
}
private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
//a few reasons that you may be interested in.
switch (reason)
{
case BackgroundTaskCancellationReason.Abort:
//app unregistered background task (amoung other reasons).
break;
case BackgroundTaskCancellationReason.Terminating:
//system shutdown
break;
case BackgroundTaskCancellationReason.ConditionLoss:
break;
case BackgroundTaskCancellationReason.SystemPolicy:
break;
}
_defferal.Complete();
}https://stackoverflow.com/questions/30429461
复制相似问题