bar*_*a_d 2 .net c# windows mobile uwp
我正在努力让扩展的执行会话适用于我的Windows Universal应用程序.
我想要实现的是以下场景.用户希望通过蓝牙将手机与设备连接.目前,每当屏幕关闭或来电或用户最小化应用程序时,连接失败,我们在恢复时重新启动它.我想为这个正在进行的连接启用扩展执行,这样即使最小化(暂停),应用程序也会继续工作.
我认为我需要ExtendedExecutionReason.Unspecified,因为它应该允许我的应用程序在暂停状态下运行长达10分钟(这对我的目的来说已经足够了).但是,连接似乎总是在挂起时失败(ExtendedExecutionRevokedReason.SystemPolicy当我尝试使用VS的应用程序生命周期下拉列表从调试器更改我的应用程序的状态时,我被撤销).我为我的应用启用了所有电池和后台权限,但仍然没有用.
我的代码大致如下:
... (on begin connection)
ClearExtendedExcecution();
DisplayRequest dr = new DisplayRequest();
var newSession = new ExtendedExecutionSession
{
Reason = ExtendedExecutionReason.Unspecified,
Description = "Pair device"
};
newSession.Revoked += SessionRevoked;
ExtendedExecutionResult result = await newSession.RequestExtensionAsync();
dr.RequestActive();
try
{
switch (result)
{
case ExtendedExecutionResult.Allowed:
m_extendedExecutionSession = newSession;
// DO WORK HERE
await ConnectDeviceAsync(token);
break;
default:
case ExtendedExecutionResult.Denied:
// fallback to request screen active if extended execution fails, but still do work
newSession.Dispose();
await ConnectDeviceAsync(token);
break;
}
}
finally
{
dr.RequestRelease();
ClearExtendedExcecution();
}
...
private async void SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
{
await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
switch (args.Reason)
{
case ExtendedExecutionRevokedReason.Resumed:
Logger.Debug("Extended execution revoked due to returning to foreground.");
break;
case ExtendedExecutionRevokedReason.SystemPolicy:
Logger.Debug("Extended execution revoked due to system policy.");
break;
}
});
}
private void ClearExtendedExcecution()
{
if (m_extendedExecutionSession == null)
{
return;
}
m_extendedExecutionSession.Revoked -= SessionRevoked;
m_extendedExecutionSession.Dispose();
m_extendedExecutionSession = null;
}
Run Code Online (Sandbox Code Playgroud)
关于我做错了什么,如何使用扩展执行会话或如何调试应用程序生命周期(没有得到系统策略撤销)的任何提示将不胜感激.谢谢!
在这种情况下,VS中的"Suspend"生命周期事件由于资源不足而模拟暂停,因此这就是为什么你得到"SystemPolicy"的原因.
如果您在没有附加调试器的情况下运行应用程序,则将其最小化(桌面)或切换到另一个应用程序(电话),执行将继续,但是(!)当您恢复应用程序时,会话因"恢复"原因而被撤销,您必须通过调用RequestExtensionAsync()方法再次启动会话.
只要您需要,此技术可确保您的执行处于活动状态.