Aggiornare un riquadro animato da un'attività in background

API importanti

Usare un'attività in background per aggiornare il riquadro animato della tua app con nuovi contenuti.

Ecco un video che illustra come aggiungere riquadri animati alle app.

Creare il progetto di attività in background

Per abilitare un riquadro animato per l'app, aggiungere un nuovo progetto di componente Windows Runtime alla soluzione. Si tratta di un assembly separato che il sistema operativo carica ed esegue in background quando un utente installa l'app.

  1. In Esplora soluzioni fare clic con il pulsante destro del mouse sulla soluzione scegliere Aggiungi, quindi fare clic su Nuovo progetto.
  2. Nella finestra di dialogo Aggiungi nuovo progetto selezionare il modello componente Windows Runtime nella sezione Linguaggi installati >> Visual C# > Universale di Windows.
  3. Assegnare al progetto il nome BackgroundTasks e toccare o fare clic su OK. Microsoft Visual Studio aggiunge il nuovo progetto alla soluzione.
  4. Nel progetto principale aggiungere un riferimento al progetto BackgroundTasks.

Implementare l'attività in background

Implementare l'interfaccia IBackgroundTask per creare una classe che aggiorna il riquadro animato dell'app. Il lavoro in background passa al metodo Run. In questo caso, l'attività ottiene un feed di diffusione per i blog MSDN. Per evitare che l'attività venga chiusa prematuramente mentre il codice asincrono è ancora in esecuzione, ottenere un differire.

  1. In Esplora soluzioni rinominare il file generato automaticamente, Class1.cs, in BlogFeedBackgroundTask.cs.
  2. In BlogFeedBackgroundTask.cs sostituire il codice generato automaticamente con il codice stub per la classe BlogFeedBackgroundTask .
  3. Nell'implementazione del metodo Run aggiungere il codice per i metodi GetMSDNBlogFeed e 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";
    }
}

Configurare il manifesto del pacchetto

Per configurare il manifesto del pacchetto, aprirlo e aggiungere una nuova dichiarazione di attività in background. Impostare il punto di ingresso per l'attività sul nome della classe, incluso il relativo spazio dei nomi.

  1. In Esplora soluzioni aprire Package.appxmanifest.
  2. Fare clic o toccare la scheda Dichiarazioni .
  3. In Dichiarazioni disponibili selezionare BackgroundTasks e fare clic su Aggiungi. Visual Studio aggiunge BackgroundTasks in Dichiarazioni supportate.
  4. In Tipi di attività supportati verificare che Timer sia selezionato.
  5. In Impostazioni app impostare il punto di ingresso su BackgroundTasks.BlogFeedBackgroundTask.
  6. Fare clic o toccare la scheda Interfaccia utente dell'applicazione .
  7. Impostare Notifiche della schermata di blocco su Badge e Testo riquadro.
  8. Impostare un percorso su un'icona a 24x24 pixel nel campo Logo badge. Importante Questa icona deve usare solo pixel monocromatici e trasparenti.
  9. Nel campo Logo piccolo impostare un percorso su un'icona a 30x30 pixel.
  10. Nel campo Logo wide impostare un percorso su un'icona di 310x150 pixel.

Registrare l'attività in background

Creare un backgroundTaskBuilder per registrare l'attività.

Nota A partire da Windows 8.1, i parametri di registrazione delle attività in background vengono convalidati al momento della registrazione. Se uno dei parametri di registrazione non è valido, viene restituito un errore. L'app deve essere in grado di gestire scenari in cui la registrazione delle attività in background ha esito negativo, ad esempio usare un'istruzione condizionale per verificare la presenza di errori di registrazione e quindi ripetere la registrazione non riuscita usando valori di parametro diversi.  

Nella pagina principale dell'app aggiungere il metodo RegisterBackgroundTask e chiamarlo nel gestore eventi 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";
    }
}

Eseguire il debug dell'attività in background

Per eseguire il debug dell'attività in background, impostare un punto di interruzione nel metodo Run dell'attività. Nella barra degli strumenti Percorso di debug selezionare l'attività in background. In questo modo il sistema chiama immediatamente il metodo Run.

  1. Impostare un punto di interruzione nel metodo Run dell'attività.
  2. Premere F5 o toccare Debug > Avvia debug per distribuire ed eseguire l'app.
  3. Dopo l'avvio dell'app, tornare a Visual Studio.
  4. Verificare che la barra degli strumenti Percorso di debug sia visibile. Si tratta del menu Visualizza > barre degli strumenti .
  5. Sulla barra degli strumenti Percorso di debug fare clic sull'elenco a discesa Sospendi e selezionare BlogFeedBackgroundTask.
  6. Visual Studio sospende l'esecuzione in corrispondenza del punto di interruzione.
  7. Premere F5 o toccare Debug > Continua per continuare a eseguire l'app.
  8. Premere MAIUSC+F5 o toccare Debug > Arresta debug per arrestare il debug.
  9. Tornare al riquadro dell'app nella schermata Start. Dopo alcuni secondi, le notifiche dei riquadri vengono visualizzate nel riquadro dell'app.