백그라운드 작업의 라이브 타일 업데이트

중요 API

백그라운드 작업을 사용하여 앱의 라이브 타일을 새 콘텐츠로 업데이트합니다.

다음 비디오는 앱에 라이브 타일을 추가하는 방법을 보여 줍니다.

백그라운드 작업 프로젝트 생성하기

앱에 라이브 타일을 사용하도록 설정하려면 새 Windows 런타임 구성 요소 프로젝트를 솔루션에 추가합니다. 이는 사용자가 앱을 설치할 때 OS가 백그라운드에서 로드하고 실행하는 별도의 어셈블리입니다.

  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(실행) 메서드 구현 시 GetMSDNBlogFeed 메서드 및 UpdateTile 메서드에 맞는 코드를 추가하세요.
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. 시작 화면에서 앱의 타일로 돌아가세요. 몇 초 후에 타일 알림이 앱의 타일에 표시됩니다.