從背景工作更新動態磚

重要 API

使用背景工作來更新含有最新內容的應用程式動態磚。

以下影片示範如何將動態磚新增至您的應用程式。

建立背景工作專案

若要為您的應用程式啟用動態磚,請將新的 Windows 執行階段元件專案新增至您的解決方案。 這是作業系統在使用者安裝應用程式時,會在背景載入並執行的不同元件。

  1. 在方案總管中,以滑鼠右鍵按一下方案,按一下 [新增],然後按一下 [新增專案]。
  2. 在 [新增專案] 對話方塊中,在 [已安裝>] - [其他語言 >Visual C# > Windows 通用] 部分選擇 [Windows 執行階段元件] 範本。
  3. 將專案命名為 BackgroundTasks,然後按一下或點選 [確定]。 Microsoft Visual Studio 會將新專案新增至方案。
  4. 在主要專案中,新增 BackgroundTasks 專案的參考。

實作背景工作

實作 IBackgroundTask 介面,以建立可更新您應用程式動態磚的類別。 您的背景工作會進入 Run 方法。 在此情況下,工作會取得 MSDN 部落格的新聞訂閱摘要。 若要防止工作在非同步程式碼仍在執行時過早關閉,請取得延遲。

  1. 在方案總管中,將自動產生的檔案 Class1.cs 重新命名為 BlogFeedBackgroundTask.cs。
  2. 在 BlogFeedBackgroundTask.cs 中,使用 BlogFeedBackgroundTask 類別的虛設常式程式碼替換自動產生的程式碼。
  3. 在 Run 方法實作中,新增 GetMSDNBlogFeedUpdateTile 方法的程式碼。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// Added during quickstart
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.Web.Syndication;

namespace BackgroundTasks
{
    public sealed class BlogFeedBackgroundTask  : IBackgroundTask
    {
        public async void Run( IBackgroundTaskInstance taskInstance )
        {
            // Get a deferral, to prevent the task from closing prematurely
            // while asynchronous code is still running.
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            // Download the feed.
            var feed = await GetMSDNBlogFeed();

            // Update the live tile with the feed items.
            UpdateTile( feed );

            // Inform the system that the task is finished.
            deferral.Complete();
        }

        private static async Task<SyndicationFeed> GetMSDNBlogFeed()
        {
            SyndicationFeed feed = null;

            try
            {
                // Create a syndication client that downloads the feed.  
                SyndicationClient client = new SyndicationClient();
                client.BypassCacheOnRetrieve = true;
                client.SetRequestHeader( customHeaderName, customHeaderValue );

                // Download the feed.
                feed = await client.RetrieveFeedAsync( new Uri( feedUrl ) );
            }
            catch( Exception ex )
            {
                Debug.WriteLine( ex.ToString() );
            }

            return feed;
        }

        private static void UpdateTile( SyndicationFeed feed )
        {
            // Create a tile update manager for the specified syndication feed.
            var updater = TileUpdateManager.CreateTileUpdaterForApplication();
            updater.EnableNotificationQueue( true );
            updater.Clear();

            // Keep track of the number feed items that get tile notifications.
            int itemCount = 0;

            // Create a tile notification for each feed item.
            foreach( var item in feed.Items )
            {
                XmlDocument tileXml = TileUpdateManager.GetTemplateContent( TileTemplateType.TileWide310x150Text03 );

                var title = item.Title;
                string titleText = title.Text == null ? String.Empty : title.Text;
                tileXml.GetElementsByTagName( textElementName )[0].InnerText = titleText;

                // Create a new tile notification.
                updater.Update( new TileNotification( tileXml ) );

                // Don't create more than 5 notifications.
                if( itemCount++ > 5 ) break;
            }
        }

        // Although most HTTP servers do not require User-Agent header, others will reject the request or return
        // a different response if this header is missing. Use SetRequestHeader() to add custom headers.
        static string customHeaderName = "User-Agent";
        static string customHeaderValue = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";

        static string textElementName = "text";
        static string feedUrl = @"http://blogs.msdn.com/b/MainFeed.aspx?Type=BlogsOnly";
    }
}

設定套件資訊清單

若要設定套件資訊清單,請開啟它並新增背景工作宣告。 將工作的進入點設定為類別名稱,包括其命名空間。

  1. 在方案總管中,開啟 Package.appxmanifest。
  2. 按一下或點選 [宣告] 索引標籤。
  3. 在 [可用宣告] 下,選擇 BackgroundTasks 並按一下 [新增]。 Visual Studio 會在 [支援的宣告] 下新增 BackgroundTasks
  4. [支援的工作類型] 下,確定 已核取 [定時器 ]。
  5. 在 [應用程式設定] 下,將進入點設定為 BackgroundTasks.BlogFeedBackgroundTask
  6. 按一下或點選 [應用程式 UI 索引標籤。
  7. 將 [鎖定畫面通知] 設定為 [徽章和磚文字]。
  8. 在 [徽章標誌] 欄位中設定 24x24 像素圖示的路徑。 重要 此圖示必須使用單色和透明像素。
  9. 在 [小標誌] 欄位中,設定 30x30 像素圖示的路徑。
  10. 在 [寬標誌] 欄位中設定 310x150 像素圖示的路徑。

登錄背景工作

建立 BackgroundTaskBuilder 以註冊您的工作。

注意 從 Windows 8.1 開始,背景工作註冊參數會在註冊時進行驗證。 如果任何註冊參數無效,則會傳回錯誤。 您的應用程式必須能夠處理背景工作註冊失敗的案例,例如,使用條件陳述式來檢查註冊錯誤,然後使用不同的參數值重試失敗的註冊。  

在應用程式的主頁面中,新增 RegisterBackgroundTask 方法,並在 OnNavigatedTo 事件處理常式中呼叫它。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Syndication;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/p/?LinkID=234238

namespace ContosoApp
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo( NavigationEventArgs e )
        {
            this.RegisterBackgroundTask();
        }


        private async void RegisterBackgroundTask()
        {
            var backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
            if( backgroundAccessStatus == BackgroundAccessStatus.AllowedSubjectToSystemPolicy ||
                backgroundAccessStatus == BackgroundAccessStatus.AlwaysAllowed )
            {
                foreach( var task in BackgroundTaskRegistration.AllTasks )
                {
                    if( task.Value.Name == taskName )
                    {
                        task.Value.Unregister( true );
                    }
                }

                BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
                taskBuilder.Name = taskName;
                taskBuilder.TaskEntryPoint = taskEntryPoint;
                taskBuilder.SetTrigger( new TimeTrigger( 15, false ) );
                var registration = taskBuilder.Register();
            }
        }

        private const string taskName = "BlogFeedBackgroundTask";
        private const string taskEntryPoint = "BackgroundTasks.BlogFeedBackgroundTask";
    }
}

偵錯背景工作

若要偵錯背景工作,請在工作的 Run 方法中設定中斷點。 在 [偵錯位置] 工具列中,選取您的背景工作。 這會導致系統立即呼叫 Run 方法。

  1. 在工作的 Run 方法中設定中斷點。
  2. 按 F5 或點選 [偵錯 > 開始偵錯] 以部署和執行應用程式。
  3. 應用程式啟動之後,切換回 Visual Studio。
  4. 確定有看見 [偵錯位置] 工具列。 其位於 [檢視 > 工具列] 功能表上。
  5. 在 [偵錯位置] 工具列上,按一下 [暫停] 下拉式清單,然後選取 [BlogFeedBackgroundTask]。
  6. Visual Studio 會在中斷點暫停執行。
  7. 按 F5 或點選 [偵錯 > 繼續] 以繼續執行應用程式。
  8. 按 Shift+F5 或點選 [偵錯 > 停止偵錯] 以停止偵錯。
  9. 返回開始畫面上的應用程式磚。 幾秒鐘後,應用程式磚上會出現通知。