[源碼下載]
html
做者:webabcd
介紹
背水一戰 Windows 10 之 後臺任務html5
示例
演示後臺任務的應用(前臺程序激活後臺任務)
/BackgroundTaskLib/BackgroundTaskFore.csc++
/* * 後臺任務,用於演示如何在前臺程序經過 api 激活後臺任務 */ using System; using System.Threading.Tasks; using Windows.ApplicationModel.Background; using Windows.Storage; namespace BackgroundTaskLib { // 實現 IBackgroundTask 接口,其只有一個方法,即 Run() public sealed class BackgroundTaskFore : IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { // 後臺任務在執行中被終止執行時所觸發的事件 taskInstance.Canceled += taskInstance_Canceled; // 異步操做 BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { // 指定後臺任務的進度 taskInstance.Progress = 0; // taskInstance.InstanceId - 後臺任務實例的惟一標識,由系統生成,與前臺的 IBackgroundTaskRegistration.TaskId 一致 StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdBackgroundTask\fore.txt", CreationCollisionOption.ReplaceExisting); for (uint progress = 10; progress <= 100; progress += 10) { await Task.Delay(1000); // 更新後臺任務的進度(會通知給前臺) taskInstance.Progress = progress; // 寫入相關數據到指定的文件 await FileIO.AppendTextAsync(file, "progress: " + progress.ToString() + ", currentTime: " + DateTime.Now.ToString() + Environment.NewLine); } } finally { // 完成異步操做 deferral.Complete(); } } void taskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { /* * BackgroundTaskCancellationReason - 後臺任務在執行中被終止執行的緣由 * Abort - 前臺 app 調用了 IBackgroundTaskRegistration.Unregister(true) * Terminating - 由於系統策略,而被終止 * LoggingOff - 由於用戶註銷系統而被取消 * ServicingUpdate - 由於 app 更新而被取消 * ... - 還有好多,參見文檔吧 */ } } }
BackgroundTask/Fore.xamlweb
<Page x:Class="Windows10.BackgroundTask.Fore" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Windows10.BackgroundTask" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="Transparent"> <StackPanel Margin="10 0 10 10"> <TextBlock Name="lblMsg" Margin="5" /> <Button Name="btnRegister" Content="註冊一個後臺任務" Margin="5" Click="btnRegister_Click" /> <Button Name="btnUnregister" Content="註銷指定的後臺任務" Margin="5" Click="btnUnregister_Click" /> <Button Name="btnRequest" Content="激活後臺任務" Margin="5" Click="btnRequest_Click" /> </StackPanel> </Grid> </Page>
BackgroundTask/Fore.xaml.csexpress
/* * 演示後臺任務的應用(前臺程序激活後臺任務) * * 注: * 一、須要引用後臺任務項目,相關代碼參見 BackgroundTaskLib/BackgroundTaskFore.cs * 二、須要在 Package.appxmanifest 添加「後臺任務」聲明,支持的任務類型選擇「常規」,並指定 EntryPoint(後臺任務的類全名),相似以下: * <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTaskLib.BackgroundTaskFore"> * <BackgroundTasks> * <Task Type="general" /> * </BackgroundTasks> * </Extension> */ using System; using System.Collections.Generic; using Windows.ApplicationModel; using Windows.ApplicationModel.Background; using Windows.Storage; using Windows.UI.Core; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Windows10.BackgroundTask { public sealed partial class Fore : Page { // 所註冊的後臺任務的名稱 private string _taskName = "Fore"; // 所註冊的後臺任務的 EntryPoint,即後臺任務的類全名 private string _taskEntryPoint = "BackgroundTaskLib.BackgroundTaskFore"; // 後臺任務是否已在系統中註冊 private bool _taskRegistered = false; // 後臺任務執行情況的進度說明 private string _taskProgress = ""; // 實例化一個 ApplicationTrigger 類型的後臺任務觸發器(由前臺程序經過 api 激活後臺任務) private ApplicationTrigger applicationTrigger = new ApplicationTrigger(); public Fore() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { // 遍歷全部已註冊的後臺任務(避免重複註冊) foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == _taskName) { // 若是找到了指定的後臺任務,則爲其增長 Progress 和 Completed 事件監聽,以便前臺 app 接收後臺任務的進度彙報和完成彙報 AttachProgressAndCompletedHandlers(task.Value); _taskRegistered = true; break; } } UpdateUI(); } private async void btnRegister_Click(object sender, RoutedEventArgs e) { // 在註冊後臺任務以前,須要調用 BackgroundExecutionManager.RequestAccessAsync(),若是是更新過的 app 則在以前還須要調用 BackgroundExecutionManager.RemoveAccess() string appVersion = $"{Package.Current.Id.Version.Major}.{Package.Current.Id.Version.Minor}.{Package.Current.Id.Version.Build}.{Package.Current.Id.Version.Revision}"; if ((string)ApplicationData.Current.LocalSettings.Values["AppVersion"] != appVersion) { // 對於更新的 app 來講先要調用這個方法 BackgroundExecutionManager.RemoveAccess(); // 註冊後臺任務以前先要調用這個方法,並獲取 BackgroundAccessStatus 狀態 BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync(); if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.DeniedBySystemPolicy || status == BackgroundAccessStatus.DeniedByUser) { // 無權限註冊後臺任務 await new MessageDialog("沒有權限註冊後臺任務").ShowAsync(); } else { // 有權限註冊後臺任務 ApplicationData.Current.LocalSettings.Values["AppVersion"] = appVersion; } } // 用於構造一個後臺任務 BackgroundTaskBuilder builder = new BackgroundTaskBuilder(); builder.Name = _taskName; // 後臺任務的名稱 builder.TaskEntryPoint = _taskEntryPoint; // 後臺任務入口點,即後臺任務的類全名 builder.SetTrigger(applicationTrigger); // 指定後臺任務的觸發器類型爲 ApplicationTrigger(由前臺程序經過 api 激活後臺任務) // 向系統註冊此後臺任務 BackgroundTaskRegistration task = builder.Register(); // 爲此後臺任務增長 Progress 和 Completed 事件監聽,以便前臺 app 接收後臺任務的進度彙報和完成彙報 AttachProgressAndCompletedHandlers(task); _taskRegistered = true; UpdateUI(); } private void btnUnregister_Click(object sender, RoutedEventArgs e) { // 遍歷全部已註冊的後臺任務 foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == _taskName) { // 從系統中註銷指定的後臺任務。惟一一個參數表明若是當先後臺任務正在運行中,是否須要將其取消 task.Value.Unregister(true); break; } } _taskRegistered = false; UpdateUI(); } private async void btnRequest_Click(object sender, RoutedEventArgs e) { // 激活後臺任務 await applicationTrigger.RequestAsync(); } private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task) { // 爲任務增長 Progress 和 Completed 事件監聽,以便前臺 app 接收後臺任務的進度彙報和完成彙報 task.Progress += new BackgroundTaskProgressEventHandler(OnProgress); task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted); } private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args) { // 獲取後臺任務的執行進度 _taskProgress = args.Progress.ToString(); UpdateUI(); } private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args) { // 後臺任務已經執行完成 _taskProgress = "完成"; // 若是這次後臺任務的執行出現了錯誤,則調用 CheckResult() 後會拋出異常 try { args.CheckResult(); } catch (Exception ex) { _taskProgress = ex.ToString(); } UpdateUI(); } private async void UpdateUI() { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { btnRegister.IsEnabled = !_taskRegistered; btnUnregister.IsEnabled = _taskRegistered; if (_taskProgress != "") lblMsg.Text = "進度:" + _taskProgress; }); } } }
OK
[源碼下載]windows