Inheritance: ISystemTrigger, IBackgroundTrigger
        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>
        /// 屏幕点亮时执行该任务: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 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...
            }
        }
 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();
 }
        async Task RegisterTask()
        {
            // Rumour of a bug which means you have to call this before calling Request...
            BackgroundExecutionManager.RemoveAccess();

            await BackgroundExecutionManager.RequestAccessAsync();

            BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
            taskBuilder.Name = "MyBackgroundTask";
            SystemTrigger trigger = new SystemTrigger(SystemTriggerType.TimeZoneChange, false);
            taskBuilder.SetTrigger(trigger);
            taskBuilder.TaskEntryPoint = typeof(MyBackgroundTask.TheTask).FullName;
            taskBuilder.Register();

            this.GetTask();
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {

            foreach (var _task in BackgroundTaskRegistration.AllTasks)
            {
                if (_task.Value.Name == "My demo task")
                {
                    _task.Value.Unregister(true);
                }
            }


            // asking to register on lock screen
            BackgroundAccessStatus accessresult = await BackgroundExecutionManager.RequestAccessAsync();

            BGTaskMD.ExampleBackgroundTask b = new BGTaskMD.ExampleBackgroundTask();
            b.ShowToast(accessresult.ToString());

            if ((accessresult == BackgroundAccessStatus.Denied)||(accessresult == BackgroundAccessStatus.Unspecified))
            {
                return;
            }

            // just to show result of lock screen registration
            BGTaskMD.RegisterTask r = new BGTaskMD.RegisterTask();
            r.RegisterIt();


            // unregister ServicingComplete task if it was already registered
            foreach (var _task in BackgroundTaskRegistration.AllTasks)
            {
                if (_task.Value.Name == "My demo task updated")
                {
                    _task.Value.Unregister(true);
                }
            }


            // register ServicingComplete task
            SystemTrigger taskTrigger = new SystemTrigger(SystemTriggerType.ServicingComplete,false);
            var bgTaskBuilder = new BackgroundTaskBuilder();
            bgTaskBuilder.Name = "My demo task updated";
            bgTaskBuilder.TaskEntryPoint = "BGTaskMD.AppUpdateServicingCompleteTask";
            bgTaskBuilder.SetTrigger(taskTrigger);
            BackgroundTaskRegistration task = bgTaskBuilder.Register();

        }
        /// <summary>
        /// 注册拉取最新story后台任务
        /// </summary>
        private void RegisterPullLatestStoriesBackgroundTask()
        {
            string Task_NAME = "Pull Latest Stories Task";
            var taskReg = BackgroundTaskRegistration.AllTasks.Values.FirstOrDefault(t => t.Name == Task_NAME) as BackgroundTaskRegistration;
            if (taskReg != null)
            {
                return;
            }

            var task = new BackgroundTaskBuilder
            {
                Name = Task_NAME,
                TaskEntryPoint = typeof(ZhiHuDaily.UWP.Background.PullLatestStoriesBackgroundExecution).FullName
            };

            var trigger = new SystemTrigger(SystemTriggerType.UserAway, false);

            task.SetTrigger(trigger);
            var r = task.Register();
        }
Exemple #8
0
        // Handle request to register the background task
        private async void RegisterBackgroundTask_Click(object sender, RoutedEventArgs e)
        {
            // SMS is a sensitive capability and the user may be prompted for consent. If the app
            // does not obtain permission for the package to have access to SMS before the background
            // work item is run (perhaps after the app is suspended or terminated), the background
            // work item will not have access to SMS and will have no way to prompt the user for consent
            // without an active window. Here, any available SMS device is activated in order to ensure
            // consent. Your app will likely do something with the SMS device as part of its features.
            if (!hasDeviceAccess)
            {
                try
                {
                    SmsDevice smsDevice = (SmsDevice)await SmsDevice.GetDefaultAsync();
                    rootPage.NotifyUser("Successfully connnected to SMS device with account number: " + smsDevice.AccountPhoneNumber, NotifyType.StatusMessage);
                    hasDeviceAccess = true;
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser("Failed to find SMS device\n" + ex.Message, NotifyType.ErrorMessage);
                    return;
                }
            }

            try
            {
                // Create a new background task builder.
                BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();

                // Create a new SmsReceived trigger.
                SystemTrigger trigger = new SystemTrigger(SystemTriggerType.SmsReceived, false);

                // Associate the SmsReceived trigger with the background task builder.
                taskBuilder.SetTrigger(trigger);

                // Specify the background task to run when the trigger fires.
                taskBuilder.TaskEntryPoint = BackgroundTaskEntryPoint;

                // Name the background task.
                taskBuilder.Name = BackgroundTaskName;

                // Register the background task.
                BackgroundTaskRegistration taskRegistration = taskBuilder.Register();

                // Associate completed event handler with the new background task.
                taskRegistration.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);

                UpdateBackgroundTaskUIState(true);
                rootPage.NotifyUser("Registered SMS background task", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
        // Registers a background task with a network change system trigger.
        private void RegisterNetworkChangeTask()
        {
            try
            {
                // Delete previously registered network status change tasks as
                // the background triggers are persistent by nature across process
                // lifetimes.
                foreach (var cur in BackgroundTaskRegistration.AllTasks)
                {
                    Diag.DebugPrint("Deleting Background Task " + cur.Value.Name);
                    cur.Value.Unregister(true);
                }

                var myTaskBuilder = new BackgroundTaskBuilder();
                var myTrigger = new SystemTrigger(SystemTriggerType.NetworkStateChange, false);
                myTaskBuilder.SetTrigger(myTrigger);
                myTaskBuilder.TaskEntryPoint = "BackgroundTaskHelper.NetworkChangeTask";
                myTaskBuilder.Name = "Network change task";
                var myTask = myTaskBuilder.Register();
            }
            catch (Exception exp)
            {
                Diag.DebugPrint("Exception caught while setting up system event" + exp.ToString());
            }
        }
Exemple #10
0
        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();
            }
        }
Exemple #11
0
        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("心跳后台任务注册失败,可能是因为您已禁用后台任务或后台任务数量已达最大!");
                }
            });
        }
 private async void Regular_Tapped(object sender, TappedRoutedEventArgs e)
 {
     var trigger = new SystemTrigger(SystemTriggerType.UserPresent, false);
     var reg = await RegisterBackgroundTask(typeof(TheBackgroundTask.TheTask).FullName,
                                  trigger.GetType().Name, trigger, null);
 }