背水一戰 Windows 10 (115) - 後臺任務: 經過 toast 激活後臺任務, 定時激活後臺任務

[源碼下載]


html

背水一戰 Windows 10 (115) - 後臺任務: 經過 toast 激活後臺任務, 定時激活後臺任務



做者:webabcd


介紹
背水一戰 Windows 10 之 後臺任務html5

  • 經過 toast 激活後臺任務
  • 定時激活後臺任務



示例
一、演示如何經過 toast 激活後臺任務
/BackgroundTaskLib/BackgroundTaskToast.csc++

/*
 * 後臺任務,用於演示如何經過 toast 激活後臺任務 
 * 
 * ToastNotificationActionTriggerDetail - toast 觸發器信息
 *     Argument - 由 toast 傳遞過來的參數
 *     UserInput - 由 toast 傳遞過來的輸入框數據
 */

using System;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Notifications;

namespace BackgroundTaskLib
{
    public sealed class BackgroundTaskToast : IBackgroundTask
    {
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            try
            {
                // 獲取 ToastNotificationActionTriggerDetail 對象
                ToastNotificationActionTriggerDetail toastDetail = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
                if (toastDetail != null)
                {
                    string result = "";

                    result = "argument: " + toastDetail.Argument;
                    result += Environment.NewLine;

                    foreach (string key in toastDetail.UserInput.Keys)
                    {
                        result += $"key:{key}, value:{toastDetail.UserInput[key]}";
                        result += Environment.NewLine;
                    }

                    // 將獲取到的 toast 信息保存爲文件
                    StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdBackgroundTask\toast.txt", CreationCollisionOption.ReplaceExisting);
                    await FileIO.WriteTextAsync(file, result);
                }
            }
            finally
            {
                deferral.Complete();
            }
        }
    }
}

BackgroundTask/Toast.xamlweb

<Page
    x:Class="Windows10.BackgroundTask.Toast"
    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">

            <Button Name="buttonShowToast" Content="顯示 toast(點擊 toast 框或點擊 toast 中的按鈕則可激活後臺任務)" Click="buttonShowToast_Click" Margin="5" />

        </StackPanel>
    </Grid>
</Page>

BackgroundTask/Toast.xaml.csexpress

/*
 * 演示如何經過 toast 激活後臺任務
 * 
 * 注:
 * 一、須要引用後臺任務項目,相關代碼參見 BackgroundTaskLib/BackgroundTaskToast.cs
 * 二、須要在 Package.appxmanifest 添加「後臺任務」聲明,支持的任務類型選擇「常規」,並指定 EntryPoint(後臺任務的類全名),相似以下:
 * <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTaskLib.BackgroundTaskToast">
 *   <BackgroundTasks>
 *     <Task Type="general" />
 *   </BackgroundTasks>
 * </Extension>
 * 
 * 
 * 本例的 toast 的 xml 說明:
 * activationType - 經過點擊 toast 激活 app 時的激活方式,background 表明後臺方式激活
 * 其餘 toast 的相關知識點請參見:/Notification/Toast/
 */

using System;
using System.Collections.Generic;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.UI.Notifications;
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 Toast : Page
    {
        private string _taskName = "Toast";
        private string _taskEntryPoint = "BackgroundTaskLib.BackgroundTaskToast";

        public Toast()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(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;
                }
            }


            // 若是任務已註冊,則註銷
            foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> t in BackgroundTaskRegistration.AllTasks)
            {
                if (t.Value.Name == _taskName)
                {
                    t.Value.Unregister(true);
                }
            }

            BackgroundTaskBuilder builder = new BackgroundTaskBuilder
            {
                Name = _taskName,
                TaskEntryPoint = _taskEntryPoint
            };
            // 指定後臺任務的觸發器類型爲 ToastNotificationActionTrigger(即經過 toast 激活)
            builder.SetTrigger(new ToastNotificationActionTrigger());
            // 註冊後臺任務
            BackgroundTaskRegistration task = builder.Register();
        }

        // 彈出 toast 通知(點擊 toast 框或點擊 toast 中的按鈕則可激活後臺任務)
        private void buttonShowToast_Click(object sender, RoutedEventArgs e)
        {
            string toastXml = @"
                <toast activationType='background' launch='launch arguments'>
                    <visual>
                        <binding template='ToastGeneric'>
                            <text>toast - title</text>
                            <text>toast - content</text>
                        </binding>
                    </visual>
                    <actions>
                        <input type='text' id='message1' title='title1' />
                        <action content='確認' activationType='background' arguments='action arguments'/>
                    </actions>
                </toast>";

            XmlDocument toastDoc = new XmlDocument();
            toastDoc.LoadXml(toastXml);

            ToastNotification toast = new ToastNotification(toastDoc);
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }
    }
}


二、演示後臺任務的應用(定時激活後臺任務)
/BackgroundTaskLib/BackgroundTaskTime.cswindows

/*
 * 後臺任務,用於演示如何定時激活後臺任務
 */

using System;
using Windows.ApplicationModel.Background;
using Windows.Storage;

namespace BackgroundTaskLib
{
    // 實現 IBackgroundTask 接口,其只有一個方法,即 Run()
    public sealed class BackgroundTaskTime : IBackgroundTask
    {
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // 異步操做
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            try
            {
                // 寫入相關數據到文件
                StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdBackgroundTask\time.txt", CreationCollisionOption.ReplaceExisting);
                await FileIO.AppendTextAsync(file, "background task timeTrigger or maintenanceTrigger: " + DateTime.Now.ToString() + Environment.NewLine);

            }
            finally
            {
                // 完成異步操做
                deferral.Complete();
            }
        }
    }
}

BackgroundTask/Time.xamlapp

<Page
    x:Class="Windows10.BackgroundTask.Time"
    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">

            <Button Name="btnRegister" Content="註冊一個後臺任務" Margin="5" Click="btnRegister_Click" />
            <Button Name="btnUnregister" Content="註銷指定的後臺任務" Margin="5" Click="btnUnregister_Click" />

        </StackPanel>
    </Grid>
</Page>

BackgroundTask/Time.xaml.csasp.net

/*
 * 演示後臺任務的應用(定時激活後臺任務)
 * 
 * 注:
 * 一、須要引用後臺任務項目,相關代碼參見 BackgroundTaskLib/BackgroundTaskTime.cs
 * 二、須要在 Package.appxmanifest 添加「後臺任務」聲明,支持的任務類型選擇「計時器」,並指定 EntryPoint(後臺任務的類全名),相似以下:
 * <Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTaskLib.BackgroundTaskTime">
 *   <BackgroundTasks>
 *     <Task Type="timer" />
 *   </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 Time : Page
    {
        // 所註冊的後臺任務的名稱
        private string _taskName = "Time";

        // 所註冊的後臺任務的 EntryPoint,即後臺任務的類全名
        private string _taskEntryPoint = "BackgroundTaskLib.BackgroundTaskTime";

        // 後臺任務是否已在系統中註冊
        private bool _taskRegistered = false;

        public Time()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 遍歷全部已註冊的後臺任務
            foreach (KeyValuePair<Guid, IBackgroundTaskRegistration> task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == _taskName)
                {
                    _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()
            {
                Name = _taskName,
                TaskEntryPoint = _taskEntryPoint

            };
            // 指定後臺任務的觸發器類型爲 MaintenanceTrigger(定時激活,最小週期 15 分鐘)
            builder.SetTrigger(new MaintenanceTrigger(15, false));
            // 註冊後臺任務
            BackgroundTaskRegistration task = builder.Register();
            
            _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 UpdateUI()
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                btnRegister.IsEnabled = !_taskRegistered;
                btnUnregister.IsEnabled = _taskRegistered;
            });
        }
    }
}



OK
[源碼下載]異步

相關文章
相關標籤/搜索