uwp
Attività di background UWP
Ricerca…
Osservazioni
- Per la registrazione di un'attività in background eseguita in un processo separato, è necessario andare alla scheda "Dichiarazioni" nel Package.appxmanifest e aggiungere una nuova "Attività in background" e impostare il punto di ingresso.
- La registrazione di un'attività in background a processo singolo può essere eseguita tramite
BackgroundTaskBuilder, ma l'applicazione genererà un'eccezione se si registra un'attività due volte, quindi è necessario verificare se è già stata registrata un'attività. - L'app deve ottenere l'autorizzazione per registrare una nuova attività, questo può essere fatto chiamando
BackgroundExecutionManager.RequestAccessAsync(), ma assicurati di avere il permesso. La chiamata restituisce il tipo di accesso (BackgroundAccessStatusenum) che indicherà se si ha accesso o meno. - Le attività registrate vengono mantenute fino a quando il pacchetto non viene disinstallato, ma non guasterebbe controllare le attività necessarie ad ogni avvio, si verifica un errore!
- Quando l'applicazione viene aggiornata, viene revocata l'autorizzazione per registrare una nuova attività. Per mantenere l'app in esecuzione dopo un aggiornamento, soprattutto se è stato aggiunto un nuovo registro delle attività, è necessario rimuovere e richiedere l'accesso , tramite
BackgroundAccessManager. Un metodo per sapere se la tua app è aggiornata, è quello di registrare un'altra attività con unSystemTrigger, tipoSystemTriggerType.ServicingComplete.
Registrazione di un'attività
/// <summary>
/// Registers a background task in the system waiting to trigger
/// </summary>
/// <param name="taskName">Name of the task. Has to be unique</param>
/// <param name="taskEntryPoint">Entry point (Namespace) of the class (has to implement IBackgroundTask and has to be in a Windows Runtime Component) to start</param>
/// <param name="trigger">What has to be triggered to start the task</param>
/// <param name="condition">Optional condition. Can be null</param>
/// <param name="recreateIfExists">Should the Task be recreated if it already exists?</param>
/// <returns></returns>
public BackgroundTaskRegistration RegisterTask(string taskName, string taskEntryPoint, IBackgroundTrigger trigger, IBackgroundCondition condition = null) {
Debug.WriteLine("Try registering task: " + taskName);
var builder = new BackgroundTaskBuilder {
Name = taskName,
TaskEntryPoint = taskEntryPoint
};
builder.SetTrigger(trigger);
if (condition != null) {
builder.AddCondition(condition);
}
try {
var task = builder.Register();
Debug.WriteLine("Task successfully registered");
return task;
} catch (Exception exception) {
Debug.WriteLine("Error creating Task: " + exception);
return null;
}
}
Ottieni un'attività registrata per nome
/// <summary>
/// Gets a BackgroundTask by its name
/// </summary>
/// <param name="taskName">Name of the task to find</param>
/// <returns>The found Task or null if none found</returns>
public BackgroundTaskRegistration TaskByName(string taskName) =>
BackgroundTaskRegistration.AllTasks.FirstOrDefault(x => x.Value.Name.Equals(taskName)).Value as BackgroundTaskRegistration;
L'obiettivo
public sealed class BackgroundTask : IBackgroundTask {
private BackgroundTaskDeferral _deferral;
/// <summary>
/// Registers the listener to check if the button is pressed
/// </summary>
/// <param name="taskInstance">An interface to an instance of the background task. The system creates this instance when the task has been triggered to run.</param>
public async void Run(IBackgroundTaskInstance taskInstance) {
_deferral = taskInstance.GetDeferral();
//Do async operations here
_deferral.Complete();
}
}
Controlla se l'attività è registrata
private bool IsTaskRegistered(string taskName) =>
BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name.Equals(taskName));
Attivazione manuale di un'attività
var trigger = new ApplicationTrigger();
TaskHandlerMentionedInThisTutorial.RegisterTask(TaskName, entryPoint, trigger, null, true);
await trigger.RequestAsync();
Annullamento della registrazione di un'attività
/// <summary>
/// Unregister a single background task with given name
/// </summary>
/// <param name="taskName">task name</param>
/// <param name="cancelTask">true if task should be cancelled, false if allowed to finish</param>
public void UnregisterTask(string taskName, bool cancelTask) =>
BackgroundTaskRegistration.AllTasks.First(x => x.Value.Name.Equals(taskName)).Value?.Unregister(cancelTask);
/// <summary>
/// Unregister an active group of background tasks, which name contains given string
/// </summary>
/// <param name="taskNamePart">part of the task name</param>
/// <param name="cancelTask">true if tasks should be cancelled, false if allowed to finish</param>
public void UnregisterTasks(string taskNamePart, bool cancelTask)
{
foreach (var task in BackgroundTaskRegistration.AllTasks.Where(x => x.Value.Name.Contains(taskNamePart)))
task.Value.Unregister(cancelTask);
}
Registrare un'attività in background con trigger
L'attività in background è un ottimo modo per eseguire alcuni lavori mentre l'applicazione non è in esecuzione. Prima di poterlo utilizzare, dovrai registrarli.
Ecco un esempio di una classe di attività in background inclusa la registrazione con un trigger e una condizione e l'implementazione Esegui
public sealed class Agent : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// run the background task code
}
// call it when your application will start.
// it will register the task if not already done
private static IBackgroundTaskRegistration Register()
{
// get the entry point of the task. I'm reusing this as the task name in order to get an unique name
var taskEntryPoint = typeof(Agent).FullName;
var taskName = taskEntryPoint;
// if the task is already registered, there is no need to register it again
var registration = BackgroundTaskRegistration.AllTasks.Select(x => x.Value).FirstOrDefault(x => x.Name == taskName);
if(registration != null) return registration;
// register the task to run every 30 minutes if an internet connection is available
var taskBuilder = new BackgroundTaskBuilder();
taskBuilder.Name = taskName;
taskBuilder.TaskEntryPoint = taskEntryPoint;
taskBuilder.SetTrigger(new TimeTrigger(30, false));
taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
return taskBuilder.Register();
}
}
Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow