/// <summary> /// 增加后台任务 /// </summary> private async void addBackgroundTask() { bool taskRegistered = false; //判断是否已经注册过了 taskRegistered = BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == exampleTaskName); if (!taskRegistered) { BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); var builder = new BackgroundTaskBuilder(); builder.Name = exampleTaskName; builder.TaskEntryPoint = "Tasks.LetterBackgroundTask"; //后台触发器,可多个 builder.SetTrigger(new SystemTrigger(SystemTriggerType.NetworkStateChange, false)); builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false)); //builder.SetTrigger(new MaintenanceTrigger(15, false)); //定时后台任务 builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); BackgroundTaskRegistration task = builder.Register(); } else { var cur = BackgroundTaskRegistration.AllTasks.FirstOrDefault(x => x.Value.Name == exampleTaskName); BackgroundTaskRegistration task = (BackgroundTaskRegistration)(cur.Value); } }
/* * 在 Windows Phone 上,你必须在尝试注册任何后台任务之前调用 RequestAccessAsync */ /// <summary> /// 注册后台任务 /// </summary> /// <param name="taskEntryPoint">任务的入口点</param> /// <param name="name">任务名称</param> /// <param name="trigger">轮询时间</param> /// <param name="condition">系统事件</param> /// <returns></returns> public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition) { BackgroundTaskRegistration task = null; if (TaskRequiresBackgroundAccess(name)) { await BackgroundExecutionManager.RequestAccessAsync(); } var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); if (backgroundAccessStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity || backgroundAccessStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity) { var builder = new BackgroundTaskBuilder(); builder.Name = name; builder.TaskEntryPoint = taskEntryPoint; builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); builder.CancelOnConditionLoss = true; } task = builder.Register(); } return task; }
private async void RegisterBackgroundTasks() { var builder = new BackgroundTaskBuilder { Name = "BackgroundUpdateReadingList", TaskEntryPoint = "EasyReader.BackgroundTasks.UpdateReadingList" }; try { await BackgroundExecutionManager.RequestAccessAsync(); } catch (Exception) { } IBackgroundTrigger trigger = new TimeTrigger(15, true); builder.SetTrigger(trigger); IBackgroundCondition condition = new SystemCondition(SystemConditionType.InternetAvailable); builder.AddCondition(condition); IBackgroundTaskRegistration task = builder.Register(); task.Progress += task_Progress; task.Completed += task_Completed; }
private void RegisterTaskButton_Click(Object sender, RoutedEventArgs e) { if (GetRegisteredTask() == null) { BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); MaintenanceTrigger trigger = new MaintenanceTrigger(MAINTENANCE_INTERVAL, false); taskBuilder.SetTrigger(trigger); taskBuilder.TaskEntryPoint = PUSH_NOTIFICATIONS_TASK_ENTRY_POINT; taskBuilder.Name = PUSH_NOTIFICATIONS_TASK_NAME; SystemCondition internetCondition = new SystemCondition(SystemConditionType.InternetAvailable); taskBuilder.AddCondition(internetCondition); try { taskBuilder.Register(); rootPage.NotifyUser("Task registered", NotifyType.StatusMessage); } catch (Exception ex) { rootPage.NotifyUser("Error registering task: " + ex.Message, NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Task already registered", NotifyType.ErrorMessage); } }
private async Task RegisterTasks() { // Applications must have lock screen privileges in order to receive raw notifications var backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync(); // Make sure the user allowed privileges if (backgroundStatus != BackgroundAccessStatus.Denied && backgroundStatus != BackgroundAccessStatus.Unspecified) { var systemEventTaskBuilder = new BackgroundTaskBuilder(); var systemEventTrigger = new SystemTrigger(SystemTriggerType.InternetAvailable, false); systemEventTaskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); systemEventTaskBuilder.SetTrigger(systemEventTrigger); // Background tasks must live in separate DLL, and be included in the package manifest // Also, make sure that your main application project includes a reference to this DLL systemEventTaskBuilder.TaskEntryPoint = SystemEventTaskEntryPoint; systemEventTaskBuilder.Name = SystemEventTaskName; try { var task = systemEventTaskBuilder.Register(); task.Completed += this.SystemEventBackgroundTaskCompleted; } catch (Exception ex) { // Should probably log this somewhere... } } else { // Should probably log this somewhere... } }
/// <summary> /// The register task. /// </summary> private static async void PushNotifications() { const string PushNotificationTaskName = "ToastNotifications"; if (GetRegisteredTask(PushNotificationTaskName) != null) { return; } var ns = new NotificationStore(); ns.Register(); await BackgroundExecutionManager.RequestAccessAsync(); await ObtainLockScreenAccess(); var taskBuilder = new BackgroundTaskBuilder { Name = PushNotificationTaskName, TaskEntryPoint = typeof(PushNotificationTask).FullName }; var trigger = new PushNotificationTrigger(); taskBuilder.SetTrigger(trigger); var internetCondition = new SystemCondition(SystemConditionType.InternetAvailable); taskBuilder.AddCondition(internetCondition); try { taskBuilder.Register(); } catch (Exception exception) { } }
private async void RegisterBackgroundTasks() { var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity || access == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity) { TimeTrigger taskTrigger = new TimeTrigger(15, false); foreach (var _task in BackgroundTaskRegistration.AllTasks) { if (_task.Value.Name == "WPGetListUpdateTimer" || _task.Value.Name=="WPGetListUpdateInternet") { _task.Value.Unregister(true); } } SystemTrigger striger = new SystemTrigger(SystemTriggerType.InternetAvailable, false); var bgTaskBuilder = new BackgroundTaskBuilder(); bgTaskBuilder.Name = "WPGetListUpdateTimer"; bgTaskBuilder.TaskEntryPoint = "BackgroundTaskWinMD.WPGetListUpdateBackgroundTask"; bgTaskBuilder.SetTrigger(taskTrigger); // условие, согласно которому триггер будет выполнен только если интернет доступен SystemCondition internetCondition = new SystemCondition(SystemConditionType.InternetAvailable); bgTaskBuilder.AddCondition(internetCondition); BackgroundTaskRegistration task = bgTaskBuilder.Register(); bgTaskBuilder = new BackgroundTaskBuilder(); bgTaskBuilder.Name = "WPGetListUpdateInternet"; bgTaskBuilder.TaskEntryPoint = "BackgroundTaskWinMD.WPGetListUpdateBackgroundTask"; bgTaskBuilder.SetTrigger(striger); bgTaskBuilder.AddCondition(internetCondition); BackgroundTaskRegistration task2 = bgTaskBuilder.Register(); } }
public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition) { //always unregister for now. foreach (var bgt in BackgroundTaskRegistration.AllTasks) { bgt.Value.Unregister(true); } //in UWP, you have to ask for access. Just like in WP var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.Denied) { throw new UnauthorizedAccessException(); } var builder = new BackgroundTaskBuilder(); builder.Name = name; builder.TaskEntryPoint = taskEntryPoint; builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); builder.CancelOnConditionLoss = true; } BackgroundTaskRegistration task = builder.Register(); return task; }
private async Task RegisterBackgroundTask() { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == UPDATE_TILE_TASK_NAME) { // 已经注册后台任务。 return; } } BackgroundAccessStatus access = await BackgroundExecutionManager.RequestAccessAsync(); if (access != BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { // 没有权限。 return; } BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); // 仅在网络可用下执行后台任务。 builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); builder.Name = UPDATE_TILE_TASK_NAME; builder.TaskEntryPoint = "BingoWallpaper.BackgroundTask.UpdateTileTask"; // 每 90 分钟触发一次。 builder.SetTrigger(new TimeTrigger(90, false)); BackgroundTaskRegistration registration = builder.Register(); }
public static IAsyncOperation<BackgroundTaskRegistration> RegisterTaskAsync() { return AsyncInfo.Run(async (cancellationToken) => { if (IsTaskRegistered()) return _current; await BackgroundExecutionManager.RequestAccessAsync(); //http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.background.timetrigger.aspx IBackgroundTrigger trigger = new TimeTrigger(6*60, false); //6 hours // Builds the background task. BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = FriendlyName; builder.TaskEntryPoint = typeof(BackgroundDemoTask).FullName; builder.SetTrigger(trigger); SystemCondition condition = new SystemCondition(SystemConditionType.InternetAvailable); builder.AddCondition(condition); // Registers the background task, and get back a BackgroundTaskRegistration object // representing the registered task. _current = builder.Register(); return _current; }); }
/// <summary> /// Register a background task with the specified taskEntryPoint, name, trigger, /// and condition (optional). /// </summary> /// <param name="taskEntryPoint">Task entry point for the background task.</param> /// <param name="name">A name for the background task.</param> /// <param name="trigger">The trigger for the background task.</param> /// <param name="condition">An optional conditional event that must be true for the task to fire.</param> public static BackgroundTaskRegistration RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition) { var builder = new BackgroundTaskBuilder(); builder.Name = name; builder.TaskEntryPoint = taskEntryPoint; builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); } BackgroundTaskRegistration task = builder.Register(); UpdateBackgroundTaskStatus(name, true); // // Remove previous completion status from local settings. // var settings = ApplicationData.Current.LocalSettings; settings.Values.Remove(name); return task; }
public static async void BackRegister() { string taskName = "back_notifi"; //后台任务名称 string entryPoint = "BackPush.NotifiBackTask"; //入口点 // 检查是否许后台任务 var result = await BackgroundExecutionManager.RequestAccessAsync(); if (result == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { // 检查是否已经注册后台任务 var task = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault((t) => t.Name == taskName); // 如果未注册,则进行注册 if (task == null) { BackgroundTaskBuilder tb = new BackgroundTaskBuilder(); tb.TaskEntryPoint = entryPoint; tb.Name = taskName; // 触发器为推送通知触发器 tb.SetTrigger(new PushNotificationTrigger()); // 运行条件为网络可用 tb.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); // 注册 tb.Register(); } } }
private async void registerButton_Click(object sender, RoutedEventArgs e) { TimeTrigger timetrigger = new TimeTrigger(30, false); PushNotificationTrigger notificationTrigger = new PushNotificationTrigger(); var SampleTask = new BackgroundTaskBuilder(); //创建后台任务实例 SampleTask.Name = "Reminder"; //指定后台任务名称 SampleTask.TaskEntryPoint = "ReminderComponent.Reminder";//指定后台任务名称 SampleTask.SetTrigger(timetrigger);//指定后台任务的触发器 SystemCondition internetCondition = new SystemCondition(SystemConditionType.InternetAvailable); SampleTask.AddCondition(internetCondition); var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { BackgroundTaskRegistration task = SampleTask.Register(); task.Progress += Value_Progress; ; task.Completed += Value_Completed; ; UpdateUI("", "注册成功"); registerButton.IsEnabled = false; cancelButtton.IsEnabled = true; var settings = Windows.Storage.ApplicationData.Current.LocalSettings; settings.Values.Remove(task.Name); } else if (access == BackgroundAccessStatus.Denied)//用户禁用后台任务或后台任务数量已达最大 { await new MessageDialog("您已禁用后台任务或后台任务数量已达最大!").ShowAsync(); } }
private async Task UpdateTile() { var result = await BackgroundExecutionManager.RequestAccessAsync(); if (result == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity || result == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity) { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == TASK_NAME) task.Value.Unregister(true); //task.Value.Progress += new BackgroundTaskProgressEventHandler(OnProgress); //task.Value.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted); } BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); var condition = new SystemCondition(SystemConditionType.InternetAvailable); builder.Name = TASK_NAME; builder.AddCondition(condition); builder.TaskEntryPoint = TASK_ENTRY; builder.SetTrigger(new TimeTrigger(15, false)); var registration = builder.Register(); registration.Progress += new BackgroundTaskProgressEventHandler(task_Progress); registration.Completed += new BackgroundTaskCompletedEventHandler(task_Completed); } }
private async static Task<BackgroundTaskRegistration> RegisterBackgroundTask(Type taskEntryPoint, string taskName, IBackgroundTrigger trigger, IBackgroundCondition condition) { var status = await BackgroundExecutionManager.RequestAccessAsync(); if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.Denied) { return null; } foreach (var cur in BackgroundTaskRegistration.AllTasks) { if (cur.Value.Name == taskName) { cur.Value.Unregister(true); } } var builder = new BackgroundTaskBuilder { Name = taskName, TaskEntryPoint = taskEntryPoint.FullName }; builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); } return builder.Register(); ; }
public static BackgroundTaskRegistration RegisterBackGroundTask(string taskEntryPoint, string taskName, IBackgroundTrigger trigger, IBackgroundCondition condition) { //Check if its alterady Registrated foreach (var cur in BackgroundTaskRegistration.AllTasks) { if (cur.Value.Name == taskName) { return (BackgroundTaskRegistration)(cur.Value); } } //Register the Task var builder = new BackgroundTaskBuilder(); builder.Name = taskName; builder.TaskEntryPoint = taskEntryPoint; if (trigger != null) { builder.SetTrigger(trigger); } if (condition != null) { builder.AddCondition(condition); } BackgroundTaskRegistration task = builder.Register(); return task; }
public static async void StartNotificationTask(BgTasks targetTask,bool restart = true) { string taskName, taskEntryPoint; int refreshTime; if (targetTask == BgTasks.Notifications) { if (!Settings.EnableNotifications || !Credentials.Authenticated || Settings.SelectedApiType == ApiType.Hummingbird) return; refreshTime = Settings.NotificationsRefreshTime; taskName = NotificationsTaskName; taskEntryPoint = NotificationsTaskNamespace; } else { refreshTime = 720; //half a day taskName = TilesTaskName; taskEntryPoint = TilesTaskNamespace; } var taskRegistered = TaskRegistration.ContainsKey(targetTask); if (!taskRegistered) taskRegistered = TryFindTask(targetTask); if (taskRegistered && !restart) return; try { if (taskRegistered) TaskRegistration[targetTask].Unregister(true); var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.DeniedBySystemPolicy || access == BackgroundAccessStatus.DeniedByUser) return; var builder = new BackgroundTaskBuilder { Name = taskName, TaskEntryPoint = taskEntryPoint }; builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); builder.SetTrigger(new TimeTrigger((uint)refreshTime, false)); if (TaskRegistration.ContainsKey(targetTask)) TaskRegistration[targetTask] = builder.Register(); else TaskRegistration.Add(targetTask, builder.Register()); } catch (Exception) { //unable to register this task } }
public static void RegisterMe() { var builder = new BackgroundTaskBuilder(); builder.Name = TaskName; builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); var timer = new TimeTrigger(15, false); builder.SetTrigger(timer); builder.TaskEntryPoint = typeof(GetNotificationBackgroundTask).FullName; var task = builder.Register(); }
private static void RegisterMaintenanceBackgroundTask() { var builder = new BackgroundTaskBuilder {Name = TaskName, TaskEntryPoint = TaskEntry}; IBackgroundTrigger trigger = new TimeTrigger(15, false); builder.SetTrigger(trigger); IBackgroundCondition condition = new SystemCondition(SystemConditionType.InternetAvailable); builder.AddCondition(condition); IBackgroundTaskRegistration task = builder.Register(); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs args) { // Do not repeat app initialization when already running, just ensure that // the window is active if (args.PreviousExecutionState == ApplicationExecutionState.Running) { Window.Current.Activate(); return; } if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Create a Frame to act navigation context and navigate to the first page var rootFrame = new Frame(); SimpleIoc.Default.Register<INavigationService>(() => new NavigationService(rootFrame)); if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("SimBalanceBackgroundTask")) { //Register background worker var backgroundTaskManager = new BackgroundTaskBuilder { TaskEntryPoint = "MobileVikings.FrontEnd.BackgroundTasks.SimBalanceBackgroundTask", Name = "SimBalanceBackgroundTask" }; backgroundTaskManager.SetTrigger(new MaintenanceTrigger(15, false)); backgroundTaskManager.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); var registration = backgroundTaskManager.Register(); ApplicationData.Current.LocalSettings.Values["SimBalanceBackgroundTask"] = true; } if (ApplicationData.Current.RoamingSettings.Values["AuthorizationInfo"] == null) { if (!rootFrame.Navigate(typeof(LoginView))) { throw new Exception("Failed to create initial page"); } } else { if (!rootFrame.Navigate(typeof(MainView))) { throw new Exception("Failed to create initial page"); } } // Place the frame in the current Window and ensure that it is active Window.Current.Content = rootFrame; Window.Current.Activate(); }
async Task Register() { await BackgroundExecutionManager.RequestAccessAsync(); var builder = new BackgroundTaskBuilder(); builder.Name = "MyBackgroundTask"; var condition = new SystemCondition(SystemConditionType.InternetAvailable); var trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false); builder.TaskEntryPoint = typeof(MyBackgroundTask.TimeZoneTask).FullName; builder.AddCondition(condition); builder.SetTrigger(trigger); builder.Register(); }
private async Task RegisterTaskAsync(string taskName, string taskNamespace) { var requestAccess = await BackgroundExecutionManager.RequestAccessAsync(); if (requestAccess == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || requestAccess == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { var taskBuilder = new BackgroundTaskBuilder { Name = taskName, TaskEntryPoint = string.Format("{0}.{1}", taskNamespace, taskName) }; // Set the condition trigger that feels right for you taskBuilder.SetTrigger(new TimeTrigger(15, false)); taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); taskBuilder.AddCondition(new SystemCondition(SystemConditionType.UserNotPresent)); taskBuilder.Register(); } }
private BackgroundTaskRegistration CreateTask(string taskEntryPoint, string name, IBackgroundTrigger trigger, IBackgroundCondition condition = null) { var builder = new BackgroundTaskBuilder(); builder.Name = name; builder.TaskEntryPoint = taskEntryPoint; builder.SetTrigger(trigger); if (condition != null) builder.AddCondition(condition); var task = builder.Register(); return task; }
public static BackgroundTaskRegistration RegisterBackgroundTask() { BacgroundTaskSetup(); deleteAllBackground(); var builder = new BackgroundTaskBuilder(); builder.Name = taskName; builder.TaskEntryPoint = entryPoint; builder.SetTrigger(Trigger); if (userCondition != null) { builder.AddCondition(userCondition); } BackgroundTaskRegistration task = builder.Register(); return task; }
public async static Task<BackgroundTaskRegistration> RegisterBackgroundTask(string taskEntryPoint, string name, IBackgroundTrigger trigger, IBackgroundCondition condition) { var builder = new BackgroundTaskBuilder { Name = name, TaskEntryPoint = taskEntryPoint }; builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); } BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); BackgroundTaskRegistration task = builder.Register(); return task; }
/// <summary> /// Register a background task with the specified taskEntryPoint, name, trigger, /// and condition (optional). /// </summary> /// <param name="taskEntryPoint">Task entry point for the background task.</param> /// <param name="name">A name for the background task.</param> /// <param name="trigger">The trigger for the background task.</param> /// <param name="condition">An optional conditional event that must be true for the task to fire.</param> public static BackgroundTaskRegistration RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition) { var builder = new BackgroundTaskBuilder(); builder.Name = name; builder.TaskEntryPoint = taskEntryPoint; builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); } BackgroundTaskRegistration task = builder.Register(); return task; }
public static async void RegisterBackgroundTask(uint minuteInterval) { var taskName = "UnreadNotifierTask"; // Unrgister task if interval is 0 if (minuteInterval == 0) { var registeredTask = BackgroundTaskRegistration.AllTasks.FirstOrDefault(t => t.Value.Name == taskName); if (registeredTask.Value != null) registeredTask.Value.Unregister(false); return; } // Ensure that interval is at least 15 minutes if (minuteInterval < 15) minuteInterval = 15; // Check if task has already been registered if (BackgroundTaskRegistration.AllTasks.Any(t => t.Value.Name == taskName)) { // Task as already been registered. // Check if task needs to be re-registered. This is the case if the notification interval has changed. var currentInterval = Windows.Storage.ApplicationData.Current.LocalSettings.Values["currentInterval"]; if (currentInterval != null && Convert.ToUInt32(currentInterval) != minuteInterval) { // Current notification interval differs from the new one. Unregister the current task var registeredTask = BackgroundTaskRegistration.AllTasks.FirstOrDefault(t => t.Value.Name == taskName); registeredTask.Value.Unregister(false); } else { // Task has been found but does not need to get chaneged. Keep everything as it is return; } } // Register background task await BackgroundExecutionManager.RequestAccessAsync(); var builder = new BackgroundTaskBuilder(); builder.Name = taskName; builder.TaskEntryPoint = "StackOverflowNotifier.UWP.BackgroundTask.UnreadNotifierTask"; builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); builder.SetTrigger(new TimeTrigger(minuteInterval, false)); builder.Register(); }
/// <summary> /// 在此页将要在 Frame 中显示时进行调用。 /// </summary> /// <param name="e">描述如何访问此页的事件数据。 /// 此参数通常用于配置页。</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { bool taskRegistered = BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == "TaskDemo"); if (!taskRegistered) { BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); if (status != BackgroundAccessStatus.Denied) { var builder = new BackgroundTaskBuilder(); builder.Name = "TaskDemo"; builder.TaskEntryPoint = "MyTask.TaskDemo"; builder.SetTrigger(new SystemTrigger(SystemTriggerType.BackgroundWorkCostChange, false)); builder.AddCondition(new SystemCondition(SystemConditionType.UserPresent)); BackgroundTaskRegistration task = builder.Register(); } } }
/// <summary> /// Registers a background task if it doesn't already exist. /// </summary> public static void RegisterBackgroundTask(Type backgroundTaskType, IBackgroundTrigger trigger, params IBackgroundCondition[] conditions) { bool alreadyRegistered = BackgroundTaskRegistration.AllTasks.Any(kvp => kvp.Value.Name == backgroundTaskType.Name); if (!alreadyRegistered) { BackgroundTaskBuilder sessionStartedTaskBuilder = new BackgroundTaskBuilder(); sessionStartedTaskBuilder.Name = backgroundTaskType.Name; sessionStartedTaskBuilder.TaskEntryPoint = backgroundTaskType.FullName; sessionStartedTaskBuilder.SetTrigger(trigger); foreach (IBackgroundCondition condition in conditions) { sessionStartedTaskBuilder.AddCondition(condition); } var sessionRegistration = sessionStartedTaskBuilder.Register(); } }
private const int MAINTENANCE_INTERVAL = 10 * 24 * 60; // Check for channels that need to be updated every 10 days public App() { InitializeComponent(); this.Suspending += new SuspendingEventHandler(OnSuspending); if (!IsTaskRegistered()) { BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); MaintenanceTrigger trigger = new MaintenanceTrigger(MAINTENANCE_INTERVAL, false); taskBuilder.SetTrigger(trigger); taskBuilder.TaskEntryPoint = PUSH_NOTIFICATIONS_TASK_ENTRY_POINT; taskBuilder.Name = PUSH_NOTIFICATIONS_TASK_NAME; SystemCondition internetCondition = new SystemCondition(SystemConditionType.InternetAvailable); taskBuilder.AddCondition(internetCondition); taskBuilder.Register(); } }