Last active
July 18, 2016 18:58
-
-
Save deepumi/d546bca879e687db51098a5ee698fea0 to your computer and use it in GitHub Desktop.
UWP Generic background task registration calss
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace UWPBackgroundTaskDemo | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using Windows.ApplicationModel.Background; | |
using System.Linq; | |
///Helper class for regsitering multiple background task | |
public static class BackgroundTaskRegistrationHelper | |
{ | |
public async static Task<BackgroundTaskRegistration> Register<T>(IBackgroundTrigger trigger, IEnumerable<IBackgroundCondition> conditions = null) | |
{ | |
if (!await RequestAccess()) return null; | |
var taskName = typeof(T).FullName; | |
//unregister the task | |
BackgroundTaskRegistration.AllTasks | |
.Select(t => t.Value) | |
.FirstOrDefault(t => t.Name.Equals(taskName)) | |
?.Unregister(true); | |
return RegisterInternal<T>(trigger, taskName,conditions); | |
} | |
private static BackgroundTaskRegistration RegisterInternal<T>(IBackgroundTrigger trigger, string taskName, IEnumerable<IBackgroundCondition> conditions) | |
{ | |
var task = new BackgroundTaskBuilder | |
{ | |
Name = taskName, | |
CancelOnConditionLoss = false, | |
TaskEntryPoint = taskName | |
}; | |
task.SetTrigger(trigger); | |
if (conditions != null) | |
{ | |
foreach (var condition in conditions) task.AddCondition(condition); | |
} | |
return task.Register(); | |
} | |
private static async Task<bool> RequestAccess() | |
{ | |
await BackgroundExecutionManager.RequestAccessAsync(); | |
switch (BackgroundExecutionManager.GetAccessStatus()) | |
{ | |
case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity: | |
case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity: | |
break; | |
case BackgroundAccessStatus.Denied: | |
case BackgroundAccessStatus.Unspecified: | |
return false; | |
} | |
return true; | |
} | |
} | |
} | |
/* | |
XAML usage | |
protected async override void OnNavigatedTo(NavigationEventArgs e) | |
{ | |
try | |
{ | |
await BackgroundTaskRegistrationHelper.Register<UWPBackgroundTask.UpdateBadgeTask>(new TimeTrigger(15, false)); | |
await BackgroundTaskRegistrationHelper.Register<UWPBackgroundTask.AnotherBackgroundTask>(new TimeTrigger(15, false)); | |
} | |
catch (Exception exp) | |
{ | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment