|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Windows.ApplicationModel.Activation; |
| 7 | +using Windows.ApplicationModel.Background; |
| 8 | + |
| 9 | +namespace Xamarin.Essentials.Background |
| 10 | +{ |
| 11 | + public static partial class Background |
| 12 | + { |
| 13 | + const string backServiceName = "BackgroundService"; |
| 14 | + |
| 15 | + internal static void PlatformStart() |
| 16 | + { |
| 17 | + Task.Run(StartBackgroundServiceAsync); |
| 18 | + } |
| 19 | + |
| 20 | + public static async Task OnBackgroundActivated(BackgroundActivatedEventArgs args) |
| 21 | + { |
| 22 | + var deferral = args.TaskInstance.GetDeferral(); |
| 23 | + await StartJobs(); |
| 24 | + deferral.Complete(); |
| 25 | + } |
| 26 | + |
| 27 | + static async Task StartBackgroundServiceAsync() |
| 28 | + { |
| 29 | + var access = await BackgroundExecutionManager.RequestAccessAsync(); |
| 30 | + |
| 31 | + switch (access) |
| 32 | + { |
| 33 | + case BackgroundAccessStatus.Unspecified: |
| 34 | + case BackgroundAccessStatus.DeniedByUser: |
| 35 | + case BackgroundAccessStatus.DeniedBySystemPolicy: |
| 36 | + await StartJobs(); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + var builder = new BackgroundTaskBuilder |
| 41 | + { |
| 42 | + Name = backServiceName, |
| 43 | + IsNetworkRequested = true |
| 44 | + }; |
| 45 | + |
| 46 | + var trigger = new ApplicationTrigger(); |
| 47 | + builder.SetTrigger(trigger); |
| 48 | + |
| 49 | + var isAlreadyRegistered = BackgroundTaskRegistration.AllTasks.Any(t => t.Value?.Name == backServiceName); |
| 50 | + if (isAlreadyRegistered) |
| 51 | + { |
| 52 | + foreach (var tsk in BackgroundTaskRegistration.AllTasks) |
| 53 | + { |
| 54 | + if (tsk.Value.Name == backServiceName) |
| 55 | + { |
| 56 | + tsk.Value.Unregister(true); |
| 57 | + break; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + builder.Register(); |
| 63 | + await trigger.RequestAsync(); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments