/// <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); } }
// Example of a Background Task, not tested private async void RegisterBtn_Click(object sender, RoutedEventArgs e) { string myTaskName = "First Task"; // check if task is already registered foreach (var cur in BackgroundTaskRegistration.AllTasks) { if (cur.Value.Name == myTaskName) { Log("Task already registered", "Caution"); return; } } // Windows Phone app must call this to use trigger types (see MSDN) await BackgroundExecutionManager.RequestAccessAsync(); // register a new task BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "First Task", TaskEntryPoint = "WebServerTask.BackgroundTask" }; taskBuilder.SetTrigger(new TimeTrigger(15, true)); //taskBuilder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false)); BackgroundTaskRegistration myFirstTask = taskBuilder.Register(); await (new MessageDialog("Task registered")).ShowAsync(); }
/// <summary> /// Registers the background task that makes cortana listen to defined keywords /// </summary> private void RegisterCortanaIntegrationTask() { // Tracks whether the background task has been registerd or not. bool taskRegistered = false; string taskName = "CortanaMake"; // Search background tasks registrations for the task name foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == taskName) { taskRegistered = true; break; } } // Register the task if it hasn't already been registered if(!taskRegistered) { BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = taskName; builder.TaskEntryPoint = "BackgroundComponent"; // This is the name of a background task that needs to get created. When the task is run, // the public void Run(IBackgroundTaskInstance taskInstance) will be called in this library. // We also have to register this in our app manifest. builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false)); BackgroundTaskRegistration task = builder.Register(); task.Completed += new BackgroundTaskCompletedEventHandler(OnCortanaMakeTaskCompleted); } }
/// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; var taskRegistered = false; foreach (var task in Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "BaconographyW8BackgroundTaskLiveTileUpdater") { taskRegistered = true; break; } } if (!taskRegistered) { var builder = new BackgroundTaskBuilder(); builder.Name = "BaconographyW8BackgroundTaskLiveTileUpdater"; builder.TaskEntryPoint = "BaconographyW8BackgroundTask.LiveTileUpdater"; builder.SetTrigger(new TimeTrigger(15, false)); builder.Register(); } }
/// <summary> /// The register push notifications. /// </summary> private static async void RegisterPushNotifications() { const string RegisterPushNotificationName = "RegisterNotifications"; const int RegistrationInterval = 10 * 24 * 60; if (GetRegisteredTask(RegisterPushNotificationName) != null) { return; } await BackgroundExecutionManager.RequestAccessAsync(); var taskBuilder = new BackgroundTaskBuilder { Name = RegisterPushNotificationName, TaskEntryPoint = typeof(RegisterPushNotificationTask).FullName }; var trigger = new TimeTrigger(RegistrationInterval, false); taskBuilder.SetTrigger(trigger); var internetCondition = new SystemCondition(SystemConditionType.InternetAvailable); taskBuilder.AddCondition(internetCondition); try { taskBuilder.Register(); } catch (Exception exception) { } }
/// <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 void StartLocationTracker() { if( CanRunAsTask() ) { BackgroundTaskBuilder geolocTaskBuilder = new BackgroundTaskBuilder(); geolocTaskBuilder.Name = SampleBackgroundTaskName; geolocTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint; // Create a new timer triggering at a 15 minute interval var trigger = new TimeTrigger( UpdateInterval, true ); // Associate the timer trigger with the background task builder geolocTaskBuilder.SetTrigger( trigger ); // Register the background task _geolocTask = geolocTaskBuilder.Register(); // Associate an event handler with the new background task _geolocTask.Completed += new BackgroundTaskCompletedEventHandler( OnCompleted ); } else { task = new LocationBackgroundTask(); timer = ThreadPoolTimer.CreatePeriodicTimer( TimerElapsed, new TimeSpan( TimeSpan.TicksPerMillisecond * 30000 ) ); } }
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 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; }
/// <summary> /// 屏幕点亮时执行该任务:UserPresent /// http://msdn.microsoft.com/library/windows/apps/windows.applicationmodel.background.systemtriggertype.aspx /// </summary> /// <param name="taskEntryPoint">后台任务名</param> public static async void Register(string taskEntryPoint) { BackgroundExecutionManager.RemoveAccess(); var status = await BackgroundExecutionManager.RequestAccessAsync(); if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.Denied) { await new MessageDialog("系统关闭了后台运行,请前往‘系统设置’进行设置").ShowAsync(); return; } else { var taskReg = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(t => t.Name.Equals(LIVETILETASK)) as BackgroundTaskRegistration; if (taskReg == null) { //注册任务 var taskBuilder = new BackgroundTaskBuilder { Name = LIVETILETASK, TaskEntryPoint = taskEntryPoint }; var trigger = new SystemTrigger(SystemTriggerType.UserPresent, false); taskBuilder.SetTrigger(trigger); taskBuilder.Register(); } else { return; } } }
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); } }
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; }
/// <summary> /// Method reponsible for registering the background task /// </summary> private async void RegisterTask() { var taskRegistered = Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks.Select(task => task.Value.Name == nameof(TileUpdaterTask)).Count() > 0; if (taskRegistered) { this.StatusLabel.Text = "Task already registered!"; } else { // Check if task is registred BackgroundAccessStatus allowed = await BackgroundExecutionManager.RequestAccessAsync(); if (allowed == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity || allowed == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity) { var task = new BackgroundTaskBuilder { Name = nameof(TileUpdaterTask), CancelOnConditionLoss = false, TaskEntryPoint = typeof(TileUpdaterTask).ToString(), }; task.SetTrigger(new TimeTrigger(15, false)); task.AddCondition(new SystemCondition(SystemConditionType.UserPresent)); task.Register(); this.StatusLabel.Text = "Task has been registered!"; } else { this.StatusLabel.Text = "Not allowd to register task!"; } } }
/// <summary> /// We proceed to register the task if it hasn't been registered yet. Otherwise, we fetch the registration /// and retrieve the ApplicationTrigger from there. /// </summary> private async void RegisterBackgroundTask() { try { if (!BackgroundTaskRegistration.AllTasks.Any(reg => reg.Value.Name == TileRegistrationName)) { // Configure task parameters BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.TaskEntryPoint = typeof(TileUpdateTask).FullName; builder.Name = TileRegistrationName; // Remember to set an ApplicationTrigger so we can run it on demand later this.backgroundTrigger = new ApplicationTrigger(); builder.SetTrigger(backgroundTrigger); builder.Register(); MessageDialog infoDialog = new MessageDialog("Background task successfully registered.", "Info"); await infoDialog.ShowAsync(); } else { // Fetch registration details and trigger if already existing var registration = BackgroundTaskRegistration.AllTasks.FirstOrDefault(reg => reg.Value.Name == TileRegistrationName).Value as BackgroundTaskRegistration; this.backgroundTrigger = registration.Trigger as ApplicationTrigger; MessageDialog infoDialog = new MessageDialog("Background task registration data successfully retrieved.", "Info"); await infoDialog.ShowAsync(); } } catch (Exception ex) { MessageDialog errorDialog = new MessageDialog("There was an error while trying to register the background task.", "Error"); errorDialog.ShowAsync(); } }
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... } }
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; }
public static async Task RegisterApplicationTrigger(Type backgroundTaskType) { var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); if (backgroundAccessStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity || backgroundAccessStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity) { var appTrigger = new ApplicationTrigger(); string taskEntryPoint = backgroundTaskType.ToString(); var backgroundTaskBuilder = new BackgroundTaskBuilder { Name = backgroundTaskType.Name, TaskEntryPoint = taskEntryPoint }; backgroundTaskBuilder.SetTrigger(appTrigger); var task = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(i => i.Name.Equals(backgroundTaskType.Name)); task?.Unregister(true); backgroundTaskBuilder.Register(); ValueSet message = new ValueSet { { "Command", "Init" } }; var result = await appTrigger.RequestAsync(message); if (result == ApplicationTriggerResult.Allowed) { Debug.WriteLine(string.Format("{0} called!", backgroundTaskType.Name)); } } }
private async void RegisterTask() { var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { // Create a new background task builder. BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); // Create a new Phone Trigger. PhoneTrigger trigger = new PhoneTrigger(PhoneTriggerType.CallOriginDataRequest, false); // Associate the phone trigger with the background task builder. taskBuilder.SetTrigger(trigger); // Specify the background task to run when the trigger fires. taskBuilder.TaskEntryPoint = MainPage.BackgroundTaskEntryPoint; // Name the background task. taskBuilder.Name = MainPage.BackgroundTaskName; // Register the background task. BackgroundTaskRegistration taskRegistration = taskBuilder.Register(); UpdateBackgroundTaskUIState(true); rootPage.NotifyUser("Registered Caller ID background task", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Background agent access denied", NotifyType.ErrorMessage); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { if (e.Parameter is int) { Pivot.SelectedIndex = (int) e.Parameter; } LiveTileToggle.IsEnabled = App.MainViewModel.SignOnSaved; NotificationsToggle.IsEnabled = App.MainViewModel.SignOnSaved; VerifyIdToggle.IsEnabled = App.MainViewModel.SignOnSaved; LiveTileToggle.IsOn = (bool) (localSettings[App.RL.GetString("TileSettingString")] ?? false); NotificationsToggle.IsOn = (bool) (localSettings[App.RL.GetString("NotificationSettingString")] ?? false); VerifyIdToggle.IsOn = (bool)(localSettings[App.RL.GetString("VerifyIdSettingString")] ?? false); if (App.MainViewModel.SignOnSaved) { string taskName = App.RL.GetString("BackgroundTaskName"); if (!IsTaskRegistered(taskName)) { var builder = new BackgroundTaskBuilder(); builder.Name = taskName; builder.TaskEntryPoint = "BackgroundUpdater.BalanceCheck"; builder.SetTrigger(new TimeTrigger(15, false)); //builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); //this doesn't work... await BackgroundExecutionManager.RequestAccessAsync(); BackgroundTaskRegistration task = builder.Register(); } } base.OnNavigatedTo(e); }
public static void Register() { foreach (var iter in BackgroundTaskRegistration.AllTasks) { IBackgroundTaskRegistration mytask = iter.Value; if (mytask.Name == "ExampleBackgroundTask") { mytask.Unregister(true); break; } } var builder = new BackgroundTaskBuilder(); PushNotificationTrigger trigger = new PushNotificationTrigger(); builder.SetTrigger(trigger); builder.Name = "ExampleBackgroundTask"; builder.TaskEntryPoint = "Usergrid.Notifications.ExampleBackgroundTask"; ExampleBackgroundTask.task = builder.Register(); task.Progress += task_Progress; task.Completed += task_Completed; }
public async void registerBackgroundTask() { try { 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); } BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = TASK_NAME; builder.TaskEntryPoint = TASK_ENTRY; builder.SetTrigger(new TimeTrigger(15, false)); var registration = builder.Register(); } for (int i = 0; i < 5; i++) { Uri u = new Uri("ms-appx:///tile/TileTemplate" + new Random().Next(1, 3).ToString() + ".xml"); StorageFile xmlFile = await StorageFile.GetFileFromApplicationUriAsync(u); XmlDocument doc = await XmlDocument.LoadFromFileAsync(xmlFile); TileNotification notifi = new TileNotification(doc); TileUpdater udt = TileUpdateManager.CreateTileUpdaterForApplication(); udt.Update(notifi); } } catch(Exception e) { System.Diagnostics.Debug.WriteLine(e.Message); } }
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(); } }
/// <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) { } }
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 StartInBackground_Click(object s, RoutedEventArgs e) { var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); var geofenceTaskBuilder = new BackgroundTaskBuilder { Name = "GeofenceBackgroundTask", TaskEntryPoint = "BackgroundTask.GeofenceBackgroundTask" }; var trigger = new LocationTrigger(LocationTriggerType.Geofence); geofenceTaskBuilder.SetTrigger(trigger); var geofenceTask = geofenceTaskBuilder.Register(); geofenceTask.Completed += (sender, args) => { var geoReports = GeofenceMonitor.Current.ReadReports(); foreach (var geofenceStateChangeReport in geoReports) { var id = geofenceStateChangeReport.Geofence.Id; var newState = geofenceStateChangeReport.NewState.ToString(); Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => new MessageDialog(newState + " : " + id) .ShowAsync()); } }; }
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(); }
private async Task<bool> RegisterBackgroundTask() { // Unregister any previous exising background task UnregisterBackgroundTask(); // Request access BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); // If denied if (status != BackgroundAccessStatus.AlwaysAllowed && status != BackgroundAccessStatus.AllowedSubjectToSystemPolicy) return false; // Construct the background task BackgroundTaskBuilder builder = new BackgroundTaskBuilder() { Name = BACKGROUND_TASK_NAME, TaskEntryPoint = "BackgroundTasks.BadgeNotificationHistoryChangedTriggerTask" }; // Set trigger for Toast History Changed builder.SetTrigger(new ToastNotificationHistoryChangedTrigger()); // And register the background task BackgroundTaskRegistration registration = builder.Register(); return true; }
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; }); }
/* * 在 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 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(); ; }