Nello script #100 abbiamo visto come monitorare quando un dispositivo entra ed esce da determinate aree, attraverso le API di Geofence, quando l'app è in esecuzione.
Questo controllo può essere eseguito anche quando un'app non è in esecuzione grazie a un IBackgroundTask e a LocationTrigger, di tipo appunto Geofence.
All'interno della classe che implementa IBackgroundTask possiamo interrogare lo stato di GeofenceMonitor e lanciare, ad esempio, una notifica toast in caso ci sia un report con stato GeofenceState.Entered.
public sealed class GeofenceNotificationTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
var reports = GeofenceMonitor.Current.ReadReports();
var report = reports.FirstOrDefault(r => r.NewState == GeofenceState.Entered);
if (report == null)
return;
var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
var txtNodes = toastXmlContent.GetElementsByTagName("text");
txtNodes[0].InnerText = "Geofence entered";
txtNodes[1].InnerText = report.Geofence.Id;
var toast = new ToastNotification(toastXmlContent);
var toastNotifier = ToastNotificationManager.CreateToastNotifier();
toastNotifier.Show(toast);
}
}La registrazione del Background Task può essere eseguita dall'app vera e propria attraverso BackgroundTaskBuilder, impostando come trigger un oggetto LocationTrigger e specificando come TaskEntryPoint il fullname del nostro IBackgroundTask.
try
{
var result = await BackgroundExecutionManager.RequestAccessAsync();
bool isRegistered = BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == "GeofenceNotificationTask");
if (!isRegistered)
{
var builder = new BackgroundTaskBuilder();
builder.Name = "GeofenceNotificationTask";
builder.TaskEntryPoint = typeof(WindowsRuntimeComponent1.GeofenceNotificationTask).FullName;
builder.SetTrigger(new LocationTrigger(LocationTriggerType.Geofence));
builder.Register();
}
}
catch (Exception ex)
{
}Commenti
Per inserire un commento, devi avere un account.
Fai il login e torna a questa pagina, oppure registrati alla nostra community.
Approfondimenti
Integrare un servizio esterno con .NET Aspire
Evidenziare una porzione di testo in un pagina dopo una navigazione
Configurare automaticamente un webhook in Azure DevOps
Disabilitare le run concorrenti di una pipeline di Azure DevOps
Raggruppare risorse in .NET Aspire
Autenticazione di git tramite Microsoft Entra ID in Azure DevOps
Supportare la sessione affinity di Azure App Service con Application Gateway
Arricchire l'interfaccia di .NET Aspire
Usare la libreria PredicateBuilder per eseguire query tramite Entity Framework che usano or su più campi
Utilizzare l'espressione if inline in una pipeline di Azure DevOps
Semplificare i deployment con le label in Azure Container App
Documentare i servizi REST con Swagger e OpenAPI con .NET 9


