Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Created November 16, 2019 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JerryNixon/f5de16d75302318912607e212e783ec7 to your computer and use it in GitHub Desktop.
Save JerryNixon/f5de16d75302318912607e212e783ec7 to your computer and use it in GitHub Desktop.
Simple, basic UWP Background Task
public class ApplicationTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance instance)
{
Debugger.Break();
}
public static async Task<IBackgroundTrigger> RegisterWithApplicationTriggerAsync(params IBackgroundCondition[] conditions)
{
var trigger = new ApplicationTrigger();
await RegisterAsync(trigger, conditions);
return trigger;
}
public static async Task<bool> RegisterAsync(IBackgroundTrigger trigger, params IBackgroundCondition[] conditions)
{
var taskName = new StackFrame().GetMethod().DeclaringType.Name;
try
{
RemoveAccess();
if (!await RequestAccessAsync())
{
throw new Exception("RequestAccessAsync returned false.");
}
UnregisterTask();
RegisterTask();
return true;
}
catch
{
return false;
}
void RemoveAccess()
{
BackgroundExecutionManager.RemoveAccess();
}
async Task<bool> RequestAccessAsync()
{
var register = await BackgroundExecutionManager.RequestAccessAsync();
switch (register)
{
case BackgroundAccessStatus.AlwaysAllowed:
case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:
return true;
case BackgroundAccessStatus.Unspecified:
case BackgroundAccessStatus.DeniedBySystemPolicy:
case BackgroundAccessStatus.DeniedByUser:
default:
return false;
}
}
void UnregisterTask()
{
foreach (var task in BackgroundTaskRegistration.AllTasks
.Where(x => x.Value.Name == taskName))
{
task.Value.Unregister(true);
}
}
void RegisterTask()
{
var builder = new BackgroundTaskBuilder
{
Name = taskName,
};
builder.SetTrigger(trigger);
foreach (var condition in conditions)
{
builder.AddCondition(condition);
}
builder.Register();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment