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 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; }
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; }); }
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 ) ); } }
public static void BacgroundTaskSetup() { Trigger = new TimeTrigger(15, false); SystemCondition userCondition = new SystemCondition(SystemConditionType.UserPresent); taskName = "SampleBackgroundTask"; entryPoint = "WindowsRuntimeComponent.SampleBackgroundTask"; }
/// <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) { } }
private async Task RegisterTask() { try { BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); if(status == BackgroundAccessStatus.Denied) { //Message aan de gebruiker. } else { BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = BackgroundTaskName; builder.TaskEntryPoint = BackgroundTaskEntryPoint; var trigger = new TimeTrigger(15, false); builder.SetTrigger(trigger); var condition = new SystemCondition(SystemConditionType.InternetAvailable); builder.AddCondition(condition); regTask = builder.Register(); regTask.Completed += RegTask_Completed; } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
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 async void Create(string backgroundTaskName, string backgroundTaskEntryPoint, int time, IBackgroundCondition backgroundCondition) { IBackgroundTrigger backgroundTrigger = new TimeTrigger((uint)time, false); var task = BackgroundTaskHelper.RegisterBackgroundTask(backgroundTaskEntryPoint, backgroundTaskName, backgroundTrigger, backgroundCondition); await task; AttachProgressAndCompletedHandlers(task.Result); }
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(); }
public async Task RegisterTask() { var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); if (backgroundAccessStatus == BackgroundAccessStatus.Denied) { return; } if (GetTask()) { return; } var timeTrigger = new TimeTrigger(15, false); var backgroundTaskBuilder = new BackgroundTaskBuilder(); backgroundTaskBuilder.Name = TASK_NAME; backgroundTaskBuilder.TaskEntryPoint = typeof(BackgroundTileTimerTask.BackgroundTask).FullName; backgroundTaskBuilder.SetTrigger(timeTrigger); backgroundTaskBuilder.Register(); }
/// <summary> /// Register the background task /// </summary> public async Task RegisterAsync() { BackgroundAccessStatus status = BackgroundExecutionManager.GetAccessStatus(); if (status == BackgroundAccessStatus.Unspecified) { BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); if (backgroundAccessStatus != BackgroundAccessStatus.Denied) { // Delete all tasks foreach (var registeredTask in BackgroundTaskRegistration.AllTasks) { registeredTask.Value.Unregister(true); } // Register new tasks foreach (var task in _tasks) { BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = task.Key, TaskEntryPoint = task.Value }; IBackgroundTrigger trigger; if (backgroundAccessStatus == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity || backgroundAccessStatus == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity) { trigger = new TimeTrigger(30, false); } else { trigger = new MaintenanceTrigger(30, false); } taskBuilder.SetTrigger(trigger); taskBuilder.Register(); } } } }
public async void BackgroundTaskCreator(string name, string entryPoint, uint time) { //clean foreach (var task in BackgroundTaskRegistration.AllTasks) if (task.Value.Name == name) task.Value.Unregister(true); //register var timerTrigger = new TimeTrigger(time, false); await BackgroundExecutionManager.RequestAccessAsync(); var builder = new BackgroundTaskBuilder(); builder.Name = name; builder.TaskEntryPoint = entryPoint; builder.SetTrigger(timerTrigger); builder.AddCondition(new SystemCondition(SystemConditionType.UserPresent)); BackgroundTaskRegistration tTask = builder.Register(); }
private void CreateChannelRenewalTrigger() { foreach ( KeyValuePair<Guid, IBackgroundTaskRegistration> BTask in BackgroundTaskRegistration.AllTasks ) { if ( BTask.Value.Name == "ChannelRenewalTrigger" ) return; } #if DEBUG TimeTrigger OneDayTrigger = new TimeTrigger( 15, false ); #else TimeTrigger OneDayTrigger = new TimeTrigger( 60, false ); #endif BackgroundTaskBuilder Builder = new BackgroundTaskBuilder(); Builder.Name = "ChannelRenewalTrigger"; Builder.TaskEntryPoint = "Tasks.ChannelRenewal"; Builder.SetTrigger( OneDayTrigger ); BackgroundTaskRegistration task = Builder.Register(); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); var keepAliveBGName = "KeepAliveBackgroundTask"; var taskRegistered = BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == keepAliveBGName); if (!taskRegistered) { var builder = new BackgroundTaskBuilder { Name = keepAliveBGName, IsNetworkRequested = true, TaskEntryPoint = typeof(KeepAliveBackgroundTask).FullName }; var trigger = new TimeTrigger(20, false); builder.SetTrigger(trigger); var task = builder.Register(); } }
public async static Task RegBGTask(uint frequency, bool isEnabled) { var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); if (backgroundAccessStatus == BackgroundAccessStatus.AlwaysAllowed || backgroundAccessStatus == BackgroundAccessStatus.AllowedSubjectToSystemPolicy) { foreach (var t in BackgroundTaskRegistration.AllTasks) { if (t.Value.Name == BACKGROUND_NAME || t.Value.Name == TOAST_HANDLER_NAME) { t.Value.Unregister(true); } } BackgroundTaskBuilder builder = new BackgroundTaskBuilder() { Name = TOAST_HANDLER_NAME, TaskEntryPoint = TOAST_HANDLER_ENTRY }; builder.SetTrigger(new ToastNotificationActionTrigger()); BackgroundTaskRegistration toastreg = builder.Register(); if (frequency < 30 || !isEnabled) { return; } TimeTrigger hourlyTrigger = new TimeTrigger(frequency, false); SystemCondition userCondition = new SystemCondition(SystemConditionType.InternetAvailable); BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder(); taskBuilder.Name = BACKGROUND_NAME; taskBuilder.TaskEntryPoint = BACKGROUND_ENTRY; taskBuilder.AddCondition(userCondition); taskBuilder.SetTrigger(hourlyTrigger); var registration = taskBuilder.Register(); } }
private async void RegisterTask() { try { BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); if(status == BackgroundAccessStatus.Denied) { //Message aan gebruiker, bevoorbeeld } else { //Taak registreren bij systeem BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = BackgroundTaskName; builder.TaskEntryPoint = BackgroundTaskEntryPoint; var trigger = new TimeTrigger(15,false);//Oneshot, 1x uitvoeren of elke 15 minuten uitvoeren? builder.SetTrigger(trigger); //Er moet iets zijn, conditie var condition = new SystemCondition(SystemConditionType.InternetAvailable);//Als er internet is builder.AddCondition(condition); regTask = builder.Register(); regTask.Completed += RegTask_Completed; } } catch(Exception ex) { Debug.WriteLine(ex.ToString()); } }
private async Task RegisterBackgroundUpdaterTask() { const int taskIntervalHours = 25; if (BackgroundTaskRegistration.AllTasks.Any(t => t.Value.Name == Constants.BackgroundUpdaterTaskName)) { // Task already registered return; } var accessStatus = await BackgroundExecutionManager.RequestAccessAsync(); if (accessStatus != BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { logger.LogMessage($"Attempted to register {Constants.BackgroundUpdaterTaskName} task, but system hasn't allowed it.", LoggingLevel.Warning); return; } var builder = new BackgroundTaskBuilder { Name = Constants.BackgroundUpdaterTaskName, TaskEntryPoint = Constants.BackgroundUpdaterTaskName + ".BackgroundUpdaterTask" }; TimeTrigger trigger = new TimeTrigger(60 * taskIntervalHours, false); builder.SetTrigger(trigger); try { BackgroundTaskRegistration task = builder.Register(); } catch (Exception ex) { logger.LogMessage($"Error registering {Constants.BackgroundUpdaterTaskName} task. {ex.Message}", LoggingLevel.Error); } logger.LogMessage($"Registered {Constants.BackgroundUpdaterTaskName} task to run every {taskIntervalHours} hours.", LoggingLevel.Information); }
/// <summary> /// This is the click handler for the 'Register' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> async private void RegisterBackgroundTask(object sender, RoutedEventArgs e) { try { // Get permission for a background task from the user. If the user has already answered once, // this does nothing and the user must manually update their preference via PC Settings. BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); // Regardless of the answer, register the background task. If the user later adds this application // to the lock screen, the background task will be ready to run. // Create a new background task builder BackgroundTaskBuilder geolocTaskBuilder = new BackgroundTaskBuilder(); geolocTaskBuilder.Name = SampleBackgroundTaskName; geolocTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint; // Create a new timer triggering at a 15 minute interval var trigger = new TimeTrigger(15, false); // 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); UpdateButtonStates(/*registered:*/ true); switch (backgroundAccessStatus) { case BackgroundAccessStatus.Unspecified: case BackgroundAccessStatus.Denied: #if WINDOWS_APP rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage); #else rootPage.NotifyUser("Not able to run in background.", NotifyType.ErrorMessage); #endif break; default: // Ensure we have presented the location consent prompt (by asynchronously getting the current // position). This must be done here because the background task cannot display UI. GetGeopositionAsync(); break; } } catch (Exception ex) { #if WINDOWS_APP // HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) == 0x80070032 const int RequestNotSupportedHResult = unchecked((int)0x80070032); if (ex.HResult == RequestNotSupportedHResult) { rootPage.NotifyUser("Location Simulator not supported. Could not get permission to add application to the lock screen, this application must be added to the lock screen before the background task will run.", NotifyType.StatusMessage); } else #endif { rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage); } UpdateButtonStates(/*registered:*/ false); } }
async private void activeLocation_Toggled(object sender, RoutedEventArgs e) { if (activeLocation.IsOn == true && _geolocTask == null) { try { BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync(); BackgroundTaskBuilder geolocTaskBuilder = new BackgroundTaskBuilder(); geolocTaskBuilder.Name = BackgroundTaskName; geolocTaskBuilder.TaskEntryPoint = BackgroundTaskEntryPoint; var trigger = new TimeTrigger(15, false); geolocTaskBuilder.SetTrigger(trigger); _geolocTask = geolocTaskBuilder.Register(); _geolocTask.Completed += OnCompleted; switch (backgroundAccessStatus) { case BackgroundAccessStatus.Unspecified: case BackgroundAccessStatus.Denied: Status.Text = "Impossible de fonctionner en arrière-plan. La demande doit être ajouté à l'écran de verrouillage."; break; default: Status.Text = "Enregister."; RequestLocationAccess(); break; } } catch (Exception ex) { Status.Text = ex.ToString(); } } if (activeLocation.IsOn == false) { if (null != _geolocTask) { _geolocTask.Unregister(true); _geolocTask = null; } MobilePosition_Latitude.Text = "Pas dedata"; MobilePosition_Longitude.Text = "Pas de data"; MobilePosition_Accuracy.Text = "Pas de data"; } }
void RegisterNewTask() { var builder = new BackgroundTaskBuilder(); builder.Name = DOWNLOAD_FEED_TASK; builder.TaskEntryPoint = DOWNLOAD_TASK_ENTRY_POINT; // Run every 15 minutes if the device has internet connectivity var trigger = new TimeTrigger(15, false); builder.SetTrigger(trigger); //auto condition =ref new SystemCondition(SystemConditionType::InternetAvailable); //builder->AddCondition(condition); builder.Register(); }
private async Task setupToast() { CheckAppVersion(); var toastTaskName = "ToastBackTask"; var taskRegistered = false; foreach (var task in Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == toastTaskName) { taskRegistered = true; break; } } if (!taskRegistered) { await Windows.ApplicationModel.Background.BackgroundExecutionManager.RequestAccessAsync(); var builder = new BackgroundTaskBuilder(); builder.Name = toastTaskName; builder.TaskEntryPoint = "Tasks.ToastBackground"; var hourlyTrigger = new TimeTrigger(30, false); builder.SetTrigger(hourlyTrigger); BackgroundTaskRegistration task = builder.Register(); } }
private async void HeartBeat_Click(object sender, RoutedEventArgs e) { if (Beating) { ContentDialog dialog = new ContentDialog() { Title = "请确认", //标题 Content = "您真的要取消心跳任务吗?",//内容 FullSizeDesired = false, //是否全屏展示 PrimaryButtonText = "是的",//第一个按钮内容 SecondaryButtonText = "算啦" }; ContentDialogResult mResult = await dialog.ShowAsync(); if (mResult == ContentDialogResult.Primary) { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "SimpleBackTask") { task.Value.Unregister(true);//删除后台任务 } } AddLog("后台任务已经成功取消!"); HeartBtn.Icon.SetValue(FontIcon.GlyphProperty, "♡"); Beating = false; } //处理第一个按钮的返回 return; } if (ConnStatusCode == 101) { TimeTrigger timetrigger = new TimeTrigger(15, false); SystemTrigger systemTrigger = new SystemTrigger(SystemTriggerType.NetworkStateChange, false); var SampleTask = new BackgroundTaskBuilder(); //创建后台任务实例 SampleTask.Name = "SimpleBackTask"; //指定后台任务名称 SampleTask.TaskEntryPoint = "Heart_Beat.SimpleTask";//指定后台的接入点 SampleTask.SetTrigger(systemTrigger);//指定后台任务的触发器 SampleTask.SetTrigger(timetrigger);//指定后台任务的触发器 var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { BackgroundTaskRegistration task = SampleTask.Register(); task.Completed += Value_Completed; task.Progress += Value_Progress; HeartBtn.Icon.SetValue(FontIcon.GlyphProperty, "♥"); AddLog("心跳后台任务已经成功注册!"); Beating = true; } else if (access == BackgroundAccessStatus.Denied)//用户禁用后台任务或后台任务数量已达最大 { Beating = false; AddLog("心跳后台任务注册失败,可能是因为您已禁用后台任务或后台任务数量已达最大!"); await new MessageDialog("心跳启动失败!详细原因请查看日志。").ShowAsync(); } } else { await new MessageDialog("您当前还没有成功通过认证!请尝试认证或者刷新网络状态!").ShowAsync(); } }
private static void EnsureUserPresentTask() { foreach (var task in BackgroundTaskRegistration.AllTasks) if (task.Value.Name == TASKNAMEUSERPRESENT) return; IBackgroundTrigger trigger = new TimeTrigger(15, false); BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = TASKNAMETIMER; builder.TaskEntryPoint = TASKENTRYPOINT; builder.SetTrigger(new SystemTrigger(SystemTriggerType.UserPresent, false)); builder.Register(); }
public async Task registerBackgroundTask() { await BackgroundExecutionManager.RequestAccessAsync(); foreach (var task in BackgroundTaskRegistration.AllTasks) { task.Value.Unregister(true); } BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = "BackGroundTask"; TimeTrigger trig = new TimeTrigger(120, false); builder.SetTrigger(trig); builder.AddCondition(new SystemCondition(SystemConditionType.FreeNetworkAvailable)); builder.TaskEntryPoint = typeof(BackGroundTask.Backgroud).FullName; BackgroundTaskRegistration register = builder.Register(); }
static IBackgroundTaskRegistration ScheduleTask() { var existingTask = FindTask(); if (existingTask != null) return existingTask; var trigger = new TimeTrigger(15, false); var builder = new BackgroundTaskBuilder(); builder.Name = TaskName; builder.TaskEntryPoint = typeof(LiveTileUpdaterTask).ToString(); builder.SetTrigger(trigger); return builder.Register(); }
static public async void Register() { try { UnregisterBackgroundTasks(); // Internet Availble if (!IsRegistered(whirlMonWatchedTaskName)) { var builder = new BackgroundTaskBuilder(); builder.Name = whirlMonWatchedTaskName; builder.TaskEntryPoint = "WhirlMonWatchedTask.MainBackground"; builder.SetTrigger(new SystemTrigger(SystemTriggerType.InternetAvailable, false)); builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); await Windows.ApplicationModel.Background.BackgroundExecutionManager.RequestAccessAsync(); backTask = builder.Register(); } // Timer if (!IsRegistered(whirlMonWatchedTaskName2)) { var builder = new BackgroundTaskBuilder(); builder.Name = whirlMonWatchedTaskName2; builder.TaskEntryPoint = "WhirlMonWatchedTask.MainBackground"; TimeTrigger minTrigger = new TimeTrigger(15, false); builder.SetTrigger(minTrigger); builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); await Windows.ApplicationModel.Background.BackgroundExecutionManager.RequestAccessAsync(); backTask = builder.Register(); } // Toast Task if (!IsRegistered(whirlMonToastTaskName)) { var builder = new BackgroundTaskBuilder(); builder.Name = whirlMonToastTaskName; builder.TaskEntryPoint = "WhirlMonWatchedTask.ToastBackground"; builder.SetTrigger(new ToastNotificationActionTrigger()); builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable)); await Windows.ApplicationModel.Background.BackgroundExecutionManager.RequestAccessAsync(); backTask = builder.Register(); } } catch (Exception x) { WhirlPoolAPIClient.ShowToast("Register Background Task:" + x.Message); } return; }
/// <summary> /// Creates secondary tile if it is not yet created or removes the tile if it already exists. /// </summary> /// <param name="sender">Sender object</param> /// <param name="e">Event arguments</param> private async void ApplicationBar_PinTile(object sender, RoutedEventArgs e) { bool removeTile = SecondaryTile.Exists(TILE_ID); if (removeTile) { await RemoveBackgroundTaskAsync("StepTriggered"); } else { ApiSupportedCapabilities caps = await SenseHelper.GetSupportedCapabilitiesAsync(); // Use StepCounterUpdate to trigger live tile update if it is supported. Otherwise we use time trigger if (caps.StepCounterTrigger) { var myTrigger = new DeviceManufacturerNotificationTrigger(SenseTrigger.StepCounterUpdate, false); await RegisterBackgroundTaskAsync(myTrigger, "StepTriggered", "BackgroundTasks.StepTriggerTask"); } else { BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); IBackgroundTrigger trigger = new TimeTrigger(15, false); await RegisterBackgroundTaskAsync(trigger, "StepTriggered", "BackgroundTasks.StepTriggerTask"); } } await CreateOrRemoveTileAsync(removeTile); }
private async void UpdateTask() { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { AddLog("正在重新注册您的心跳任务……(这里本是个BUG:)"); foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == "SimpleBackTask") { task.Value.Unregister(true);//删除后台任务 } } AddLog("后台任务已经成功取消!"); TimeTrigger timetrigger = new TimeTrigger(15, false); SystemTrigger systemTrigger = new SystemTrigger(SystemTriggerType.NetworkStateChange, false); var SampleTask = new BackgroundTaskBuilder(); //创建后台任务实例 SampleTask.Name = "SimpleBackTask"; //指定后台任务名称 SampleTask.TaskEntryPoint = "Heart_Beat.SimpleTask";//指定后台的接入点 SampleTask.SetTrigger(systemTrigger);//指定后台任务的触发器 SampleTask.SetTrigger(timetrigger);//指定后台任务的触发器 var access = await BackgroundExecutionManager.RequestAccessAsync(); if (access == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity) { BackgroundTaskRegistration task = SampleTask.Register(); task.Completed += Value_Completed; task.Progress += Value_Progress; HeartBtn.Icon.SetValue(FontIcon.GlyphProperty, "♥"); AddLog("心跳后台任务已经成功注册!"); Beating = true; } else if (access == BackgroundAccessStatus.Denied)//用户禁用后台任务或后台任务数量已达最大 { Beating = false; AddLog("心跳后台任务注册失败,可能是因为您已禁用后台任务或后台任务数量已达最大!"); } }); }