Instructions pour l’utilisation du suivi des visites

La fonctionnalité Visites simplifie le processus de suivi de l’emplacement afin de le rendre plus efficace à des fins pratiques de nombreuses applications. Une visite est définie comme une zone géographique importante que l’utilisateur entre et quitte. Les visites sont similaires aux limites géographiques dans le fait qu’elles permettent à l’application d’être avertie uniquement lorsque l’utilisateur entre ou quitte certaines zones d’intérêt, ce qui élimine la nécessité d’un suivi continu de l’emplacement qui peut être un drain sur la batterie. Toutefois, contrairement aux limites géographiques, les zones de visite sont identifiées dynamiquement au niveau de la plateforme et n’ont pas besoin d’être définies explicitement par des applications individuelles. En outre, la sélection des visites d’une application est gérée par un paramètre de granularité unique, plutôt qu’en s’abonnant à des endroits individuels.

Paramétrage préliminaire

Avant d’aller plus loin, assurez-vous que votre application est capable d’accéder à l’emplacement de l’appareil. Vous devez déclarer la Location fonctionnalité dans le manifeste et appeler la méthode Geolocator.RequestAccessAsync pour vous assurer que les utilisateurs accordent les autorisations d’emplacement de l’application. Pour plus d’informations sur la procédure à suivre, consultez Obtenir l’emplacement de l’utilisateur.

N’oubliez pas d’ajouter l’espace Geolocation de noms à votre classe. Cela sera nécessaire pour que tous les extraits de code de ce guide fonctionnent.

using Windows.Devices.Geolocation;

Vérifier la dernière visite

La façon la plus simple d’utiliser la fonctionnalité de suivi des visites consiste à récupérer le dernier changement d’état lié à visit connu. Une modification d’état est un événement journalisé par plateforme dans lequel l’utilisateur entre/quitte un emplacement d’importance, il y a un mouvement significatif depuis le dernier rapport ou l’emplacement de l’utilisateur est perdu (voir l’énumération VisitStateChange ). Les modifications d’état sont représentées par les instances Geovisit. Pour récupérer l’instance Geovisit pour la dernière modification d’état enregistrée, utilisez simplement la méthode désignée dans la classe GeovisitMonitor.

Remarque

La vérification de la dernière visite enregistrée ne garantit pas que les visites sont actuellement suivies par le système. Pour suivre les visites au fur et à mesure qu’elles se produisent, vous devez les surveiller au premier plan ou vous inscrire au suivi en arrière-plan (voir les sections ci-dessous).

private async void GetLatestStateChange() {
    // retrieve the Geovisit instance
    Geovisit latestVisit = await GeovisitMonitor.GetLastReportAsync();

    // Using the properties of "latestVisit", parse out the time that the state 
    // change was recorded, the device's location when the change was recorded,
    // and the type of state change.
}

Analyser une instance Geovisit (facultatif)

La méthode suivante convertit toutes les informations stockées dans une instance Geovisit en chaîne facile à lire. Il peut être utilisé dans l’un des scénarios de ce guide pour vous aider à fournir des commentaires sur les visites signalées.

private string ParseGeovisit(Geovisit visit){
    string visitString = null;

    // Use a DateTimeFormatter object to process the timestamp. The following
    // format configuration will give an intuitive representation of the date/time
    Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatterLongTime;
    
    formatterLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter(
        "{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", 
        Windows.Globalization.CalendarIdentifiers.Gregorian, 
        Windows.Globalization.ClockIdentifiers.TwentyFourHour);
    
    // use this formatter to convert the timestamp to a string, and add to "visitString"
    visitString = formatterLongTime.Format(visit.Timestamp);

    // Next, add on the state change type value
    visitString += " " + visit.StateChange.ToString();

    // Next, add the position information (if any is provided; this will be null if 
    // the reported event was "TrackingLost")
    if (visit.Position != null) {
        visitString += " (" +
        visit.Position.Coordinate.Point.Position.Latitude.ToString() + "," +
        visit.Position.Coordinate.Point.Position.Longitude.ToString() + 
        ")";
    }

    return visitString;
}

Surveiller les visites au premier plan

La classe GeovisitMonitor utilisée dans la section précédente gère également le scénario d’écoute des modifications d’état sur une période donnée. Pour ce faire, instanciez cette classe, inscrivez une méthode de gestionnaire pour son événement et appelez la Start méthode.

// this GeovisitMonitor instance will belong to the class scope
GeovisitMonitor monitor;

public void RegisterForVisits() {

    // Create and initialize a new monitor instance.
    monitor = new GeovisitMonitor();
    
    // Attach a handler to receive state change notifications.
    monitor.VisitStateChanged += OnVisitStateChanged;
    
    // Calling the start method will start Visits tracking for a specified scope:
    // For higher granularity such as venue/building level changes, choose Venue.
    // For lower granularity in the range of zipcode level changes, choose City.
    monitor.Start(VisitMonitoringScope.Venue);
}

Dans cet exemple, la OnVisitStateChanged méthode gère les rapports Visit entrants. L’instance Geovisit correspondante est passée via le paramètre d’événement.

private void OnVisitStateChanged(GeoVisitWatcher sender, GeoVisitStateChangedEventArgs args) {
    Geovisit visit = args.Visit;
    
    // Using the properties of "visit", parse out the time that the state 
    // change was recorded, the device's location when the change was recorded,
    // and the type of state change.
}

Lorsque l’application a terminé la surveillance des modifications d’état liées à visit, elle doit arrêter l’analyse et annuler l’inscription du ou des gestionnaires d’événements. Cette opération doit également être effectuée chaque fois que l’application est suspendue ou fermée.

public void UnregisterFromVisits() {
    
    // Stop the monitor to stop tracking Visits. Otherwise, tracking will
    // continue until the monitor instance is destroyed.
    monitor.Stop();
    
    // Remove the handler to stop receiving state change events.
    monitor.VisitStateChanged -= OnVisitStateChanged;
}

Surveiller les visites en arrière-plan

Vous pouvez également implémenter la surveillance de visite dans une tâche en arrière-plan, afin que l’activité liée à la visite puisse être gérée sur l’appareil même lorsque votre application n’est pas ouverte. Il s’agit de la méthode recommandée, car elle est plus polyvalente et plus économe en énergie.

Ce guide utilise le modèle dans Créer et inscrire une tâche en arrière-plan hors processus, dans laquelle les fichiers d’application principaux vivent dans un projet et le fichier de tâche en arrière-plan réside dans un projet distinct dans la même solution. Si vous débutez avec l’implémentation de tâches en arrière-plan, il est recommandé de suivre ces instructions principalement, en effectuant les substitutions nécessaires ci-dessous pour créer une tâche en arrière-plan de gestion de visite.

Remarque

Dans les extraits de code suivants, certaines fonctionnalités importantes telles que la gestion des erreurs et le stockage local sont absentes par souci de simplicité. Pour une implémentation robuste de la gestion des visites en arrière-plan, consultez l’exemple d’application.

Tout d’abord, vérifiez que votre application a déclaré des autorisations de tâche en arrière-plan. Dans l’élément Application/Extensions de votre fichier Package.appxmanifest , ajoutez l’extension suivante (ajoutez un Extensions élément s’il n’en existe pas déjà).

<Extension Category="windows.backgroundTasks" EntryPoint="Tasks.VisitBackgroundTask">
    <BackgroundTasks>
        <Task Type="location" />
    </BackgroundTasks>
</Extension>

Ensuite, dans la définition de la classe de tâche en arrière-plan, collez le code suivant. La Run méthode de cette tâche en arrière-plan transmet simplement les détails du déclencheur (qui contiennent les informations visites) dans une méthode distincte.

using Windows.ApplicationModel.Background;

namespace Tasks {
    
    public sealed class VisitBackgroundTask : IBackgroundTask {
        
        public void Run(IBackgroundTaskInstance taskInstance) {
            
            // get a deferral
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
            
            // this task's trigger will be a Geovisit trigger
            GeovisitTriggerDetails triggerDetails = taskInstance.TriggerDetails as GeovisitTriggerDetails;

            // Handle Visit reports
            GetVisitReports(triggerDetails);         

            finally {
                deferral.Complete();
            }
        }        
    }
}

Définissez la GetVisitReports méthode quelque part dans cette même classe.

private void GetVisitReports(GeovisitTriggerDetails triggerDetails) {

    // Read reports from the triggerDetails. This populates the "reports" variable 
    // with all of the Geovisit instances that have been logged since the previous
    // report reading.
    IReadOnlyList<Geovisit> reports = triggerDetails.ReadReports();

    foreach (Geovisit report in reports) {
        // Using the properties of "visit", parse out the time that the state 
        // change was recorded, the device's location when the change was recorded,
        // and the type of state change.
    }

    // Note: depending on the intent of the app, you many wish to store the
    // reports in the app's local storage so they can be retrieved the next time 
    // the app is opened in the foreground.
}

Ensuite, dans le projet principal de votre application, vous devez effectuer l’inscription de cette tâche en arrière-plan. Créez une méthode d’inscription qui peut être appelée par une action utilisateur ou est appelée chaque fois que la classe est activée.

// a reference to this registration should be declared at the class level
private IBackgroundTaskRegistration visitTask = null;

// The app must call this method at some point to allow future use of 
// the background task. 
private async void RegisterBackgroundTask(object sender, RoutedEventArgs e) {
    
    string taskName = "MyVisitTask";
    string taskEntryPoint = "Tasks.VisitBackgroundTask";

    // First check whether the task in question is already registered
    foreach (var task in BackgroundTaskRegistration.AllTasks) {
        if (task.Value.Name == taskName) {
            // if a task is found with the name of this app's background task, then
            // return and do not attempt to register this task
            return;
        }
    }
    
    // Attempt to register the background task.
    try {
        // Get permission for a background task from the user. If the user has 
        // already responded once, this does nothing and the user must manually 
        // update their preference via Settings.
        BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();

        switch (backgroundAccessStatus) {
            case BackgroundAccessStatus.AlwaysAllowed:
            case BackgroundAccessStatus.AllowedSubjectToSystemPolicy:
                // BackgroundTask is allowed
                break;

            default:
                // notify user that background tasks are disabled for this app
                //...
                break;
        }

        // Create a new background task builder
        BackgroundTaskBuilder visitTaskBuilder = new BackgroundTaskBuilder();

        visitTaskBuilder.Name = exampleTaskName;
        visitTaskBuilder.TaskEntryPoint = taskEntryPoint;

        // Create a new Visit trigger
        var trigger = new GeovisitTrigger();

        // Set the desired monitoring scope.
        // For higher granularity such as venue/building level changes, choose Venue.
        // For lower granularity in the range of zipcode level changes, choose City. 
        trigger.MonitoringScope = VisitMonitoringScope.Venue; 

        // Associate the trigger with the background task builder
        visitTaskBuilder.SetTrigger(trigger);

        // Register the background task
        visitTask = visitTaskBuilder.Register();      
    }
    catch (Exception ex) {
        // notify user that the task failed to register, using ex.ToString()
    }
}

Cela établit qu’une classe de tâche en arrière-plan appelée VisitBackgroundTask dans l’espace de noms Tasks fera quelque chose avec le type de location déclencheur.

Votre application doit maintenant être en mesure d’inscrire la tâche en arrière-plan de gestion des visites, et cette tâche doit être activée chaque fois que l’appareil enregistre une modification d’état liée à la visite. Vous devez renseigner la logique dans votre classe de tâche en arrière-plan pour déterminer ce qu’il faut faire avec ces informations de modification d’état.