Condividi tramite


Come monitorare l'avanzamento e il completamento delle attività in background (HTML)

[ Questo articolo è rivolto agli sviluppatori per Windows 8.x e Windows Phone 8.x che realizzano app di Windows Runtime. Gli sviluppatori che usano Windows 10 possono vedere Documentazione aggiornata ]

Scopri in che modo l'app può riconoscere le informazioni sull'avanzamento e sul completamento segnalate da un'attività in background. Le attività in background vengono disaccoppiate dall'app e vengono eseguite separatamente, tuttavia l'avanzamento e il completamento delle attività in background possono essere monitorate dal codice dell'app. A questo scopo, l'app sottoscrive gli eventi generati dalle attività in background che ha registrato nel sistema.

Cosa sapere

Tecnologie

Prerequisiti

Istruzioni

Passaggio 1:

  1. Crea una funzione da associare al gestore dell'evento per il completamento dell'attività in background. Questa funzione deve accettare un oggetto BackgroundTaskCompletedEventArgs e nessun altro parametro.

    Se registri una funzione localmente, puoi usare il footprint seguente:

    function OnCompleted(args)
    {
        // TODO: Add code that deals with background task completion.
    }
    

    Puoi quindi procedere alla registrazione con l'oggetto BackgroundTaskRegistration (ottenuto tramite una chiamata alla funzione Register):

    backgroundTaskRegistration.addEventListener("completed", onCompleted);
    
  2. Dovrai aggiungere il codice relativo al completamento dell'attività in background.

    L'esempio di attività in background aggiorna, ad esempio, l'interfaccia utente con lo stato di completamento salvato in LocalSettings:

    function OnCompleted(args)
    {
        // 
        // 
        // 
        backgroundTaskName = this.name;
    
        // 
        // Call a method to update the UI (beyond the scope of this example).
        // 
        UpdateUI();
    }
    
  3. Un'app avanzata può cercare le eccezioni generate dall'attività in background chiamando CheckResult.

    Il metodo incluso nell'esempio di attività in background può essere modificato come indicato di seguito per gestire le eccezioni generate dall'attività in background:

    function OnCompleted(task, args)
    {
        var settings = ApplicationData.Current.LocalSettings;
        var key = task.TaskId.ToString();
    
        try
        {
            args.CheckResult();
            BackgroundTaskSample.SampleBackgroundTaskStatus = settings.Values[key].ToString();
        }
        catch (Exception ex)
        {
            BackgroundTaskSample.SampleBackgroundTaskStatus = "Error: " + ex.Message;
        }
    
        UpdateUI();
    }
    

Passaggio 2:

  1. Crea una funzione del gestore eventi per gestire le attività in background completate. Questo codice deve seguire un footprint specifico, che accetta un oggetto IBackgroundTaskRegistration e un oggetto BackgroundTaskProgressEventArgs.

    Usa il seguente footprint per il metodo del gestore eventi per l'attività in background OnProgress.

    function OnProgress(task, args)
    {
        // TODO: Add code that deals with background task progress.
    }
    
  2. Aggiungi il codice al gestore eventi che controlla il completamento dell'attività in background.

    L'esempio di attività in background aggiorna, ad esempio, l'interfaccia utente con lo stato di avanzamento tramite il parametro args:

    function OnProgress(task, args)
    {
        var progress = "Progress: " + args.Progress + "%";
        BackgroundTaskSample.SampleBackgroundTaskProgress = progress;
        UpdateUI();
    }
    

Passaggio 3:

Registra le funzioni del gestore eventi con attività in background nuove ed esistenti.

  1. Quando l'app registra un'attività in background per la prima volta, dovrebbe registrare la ricezione degli aggiornamenti di avanzamento e completamento, nel caso in cui l'attività venisse eseguita mentre l'app è ancora attiva in primo piano.

    L'esempio di attività in background chiama, ad esempio, la seguente funzione su ogni attività in background registrata:

    
    function AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
    {
        task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
        task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
    }
    
  2. Quando l'app viene avviata o passa a una nuova pagina in cui è pertinente lo stato dell'attività in background, dovrebbe ottenere un elenco di attività in background attualmente registrate e associarle alle funzioni del gestore eventi di avanzamento e completamento. L'elenco delle attività in background attualmente registrate dall'applicazione viene gestito nella proprietà BackgroundTaskRegistration.AllTasks.

    L'esempio di attività in background usa, ad esempio, il codice seguente per associare i gestori eventi quando si passa alla pagina SampleBackgroundTask:

    
    function OnNavigatedTo(NavigationEventArgs e)
    {
        foreach (var task in BackgroundTaskRegistration.AllTasks)
        {
            if (task.Value.Name == BackgroundTaskSample.SampleBackgroundTaskName)
            {
                AttachProgressAndCompletedHandlers(task.Value);
                BackgroundTaskSample.UpdateBackgroundTaskStatus(BackgroundTaskSample.SampleBackgroundTaskName, true);
            }
        }
    
        UpdateUI();
    }
    

Argomenti correlati

Guida introduttiva: Creazione e registrazione di un'attività in background

Come eseguire il debug di un'attività in background

Supporto dell'app con attività in background

Come gestire un'attività in background annullata

Come ottenere l'elenco delle attività in background in sospeso

Come dichiarare le attività in background nel manifesto dell'applicazione

Linee guida ed elenco di controllo per le attività in background