I'm struggling to get extended execution session to work for my Windows Universal app.
What I'm trying to achieve is the following scenario. The user wants to connect the phone with a device via Bluetooth. Currently, whenever the screen turns off or an incoming call comes or the user minimizes the app, the connection fails and we restart it on resume. I'd like to enable extended execution for this in-progress connection, such that the app continues the work even when minimized (suspended).
I've figured I need the ExtendedExecutionReason.Unspecified
, as it should allow my app to run up to 10 minutes in the suspended state (which is more than enough for my purpose). However, connection always seems to fail on suspending (and I get revoked with ExtendedExecutionRevokedReason.SystemPolicy
when I try to alter the state of my app from the debugger using the Application Lifecycle dropdown of VS). I have enabled all battery and background permissions for my app, but still no good.
My code is roughly as follows:
... (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;
}
Any tips on what I am doing wrongly, how exactly the Extended Execution Session is meant to be used or how to debug the lifecycle of the app (without getting the system policy revocation) would be greatly appreciated. Thanks!