uwp
Zadania w tle UWP
Szukaj…
Uwagi
- Aby zarejestrować zadanie w tle, które działa w osobnym procesie, musisz przejść do zakładki „Deklaracje” w Package.appxmanifest i dodać nowe „Zadanie w tle” i ustawić punkt wejścia.
- Rejestracja zadania w tle z jednym procesem może być wykonana za pomocą
BackgroundTaskBuilder, ale aplikacja zgłosi wyjątek, jeśli zarejestrujesz zadanie dwukrotnie, więc musisz sprawdzić, czy zadanie zostało już zarejestrowane. - Aplikacja musi uzyskać uprawnienia do zarejestrowania nowego zadania. Można to zrobić przez wywołanie
BackgroundExecutionManager.RequestAccessAsync(), ale upewnij się, że naprawdę masz uprawnienia. Wywołanie zwraca typ dostępu (BackgroundAccessStatusenum), który wskaże, czy masz dostęp, czy nie. - Zarejestrowane zadania są przechowywane do momentu odinstalowania pakietu, ale sprawdzanie zadań przy każdym uruchomieniu nie zaszkodzi, błąd się zdarza!
- Po zaktualizowaniu aplikacji uprawnienie do zarejestrowania nowego zadania zostaje cofnięte. Aby aplikacja działała po aktualizacji, zwłaszcza jeśli dodałeś nowy rejestr zadań, musisz usunąć i poprosić o dostęp za pomocą
BackgroundAccessManager. Jedną z metod sprawdzania, czy aplikacja jest zaktualizowana, jest zarejestrowanie innego zadania wSystemTrigger, typSystemTriggerType.ServicingComplete.
Rejestracja zadania
/// <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;
}
}
Uzyskaj zarejestrowane zadanie według jego nazwy
/// <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;
Zadanie
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();
}
}
Sprawdź, czy zadanie jest zarejestrowane
private bool IsTaskRegistered(string taskName) =>
BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name.Equals(taskName));
Ręczne wyzwalanie zadania
var trigger = new ApplicationTrigger();
TaskHandlerMentionedInThisTutorial.RegisterTask(TaskName, entryPoint, trigger, null, true);
await trigger.RequestAsync();
Wyrejestrowanie zadania
/// <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);
}
Zarejestruj zadanie w tle za pomocą wyzwalacza
Zadanie w tle to świetny sposób na wykonanie pracy, gdy aplikacja nie jest uruchomiona. Zanim będziesz mógł z tego skorzystać, musisz je zarejestrować.
Oto próbka klasy zadania w tle, w tym rejestracji z wyzwalaczem i warunkiem oraz implementacji Run
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
Licencjonowany na podstawie CC BY-SA 3.0
Nie związany z Stack Overflow