Tutoriel mobile : Utilisation des notifications (iOS et Android)

De RAD Studio
Aller à : navigation, rechercher

Remonter à Tutoriels mobiles : Développement d'applications mobiles (iOS et Android)


Ce tutoriel décrit les étapes élémentaires relatives à l'utilisation des notifications sur votre périphérique mobile. Pour plus de détails, voir utilisation des notifications.

Trois notifications élémentaires ou styles d'alerte

Lorsque les utilisateurs définissent des notifications pour des apps de leurs périphériques mobiles, celles-ci peuvent être transmises par les apps sous les trois styles élémentaires suivants. La bannière apparaît rapidement, mais la boîte de dialogue d'alerte requiert que l'utilisateur la supprime.

Bannière de notification sur les périphériques mobiles

iOS

IOSNotificationBanner.PNG

Android

Android Notification.png


Dialogues d'alerte : Numéro de badge iOS et numéro de notification Android

Numéro de badge iOS
iPad
Numéro de notification Android
Android

Centre de notifications sur les périphériques mobiles

Les images suivantes illustrent le centre de notifications sur un iPad (Notification Center) et un périphérique Android (Notification Drawer), où l'utilisateur peut faire dérouler la liste des notifications récentes.

iOS

IOSNotificationCenter.PNG

Android

Android Notification Center.png

Accéder au service de notifications

RAD Studio fournit le composant TNotificationCenter qui vous permet d'accéder facilement au service de notifications.

Pour accéder au service de notifications, procédez comme suit :

  1. Créez une nouvelle application mobile :
  2. Sélectionnez le composant TNotificationCenter dans la palette d'outils et déposez-le sur le Concepteur de fiches.
  3. Vérifiez que l'unité suivante a bien été ajoutée automatiquement ajoutée au projet :
    • Pour les applications Delphi, ajoutez l'unité suivante à la clause uses si elle n'est pas présente :
    uses
      System.Notification;
    
    • Pour les applications C++, ajoutez l'opérateur include suivant dans le fichier d'en-tête du projet (fichier .h) :
    #include <System.Notification.hpp>
    

La méthode System.Notification.TNotificationCenter.CreateNotification permet de créer une instance de l'objet de classe TNotification.

Ajouter FMLocalNotificationPermission (iOS)

Afin d'utiliser les notifications sur les périphériques iOS 8+, vous devez vous assurer que la paire clé/valeur FMLocalNotificationPermission est activée sur la page Informations de version de Options de projet.

  1. Choisissez Projet > Options > Informations de version.
  2. Dans le champ Cible, sélectionnez Configuration Débogage - Périphérique iOS - Plate-forme 32 bits.
  3. Définissez le champ Valeur de FMLocalNotificationPermission sur true.
    Le paramètre FMLocalNotificationPermission active les notifications locales sur les périphériques iOS 8+ :
FMLocalNotificationPermission.png

Définir le numéro de badge d'icône et le numéro de notification à partir du code

TNotification.Number définit le numéro de badge d'icône (pour les périphériques iOS) et le numéro de notification (pour les périphériques Android).

Pour définir le numéro de badge d'icône iOS (pour Delphi ou C++) ou le numéro de notification Android (uniquement pour les apps Delphi), vous devez implémenter la méthode correspondante.

  1. Déposez un TButton sur la fiche.
  2. Dans l'inspecteur d'objets, définissez la propriété Name sur SetNumber.
  3. Créez l'événement OnClick du bouton SetNumber en double-cliquant sur le bouton.
  4. Implémentez le gestionnaire d'événement pour l'événement OnClick du bouton SetNumber en ajoutant le code suivant :
    • Pour Delphi :
    procedure TForm1.SetNumberClick(Sender: TObject);
    var
      MyNotification: TNotification;
    begin
      // Create an instance of TNotification
      MyNotification&nbsp;:= NotificationCenter1.CreateNotification;
      try
          // --- your code goes here ---
          // Set the icon or notification number
          MyNotification.Number&nbsp;:=18;
          // Set the alert message
          MyNotification.AlertBody&nbsp;:= 'Delphi for your mobile device is here!';
          // Note: You must send the notification to the notification center for the Icon Badge Number to be displayed.
          NotificationCenter1.PresentNotification(MyNotification);
      finally
        MyNotification.DisposeOf;
      end;
    end;
    
    • Pour C++ :
    void __fastcall TForm1::SetNumberClick(TObject *Sender)
    {
            if (NotificationCenter1->Supported()) {
                    TNotification *myNotification = NotificationCenter1->CreateNotification();
                    __try {
                            myNotification->Number = 18;
                            myNotification->AlertBody = "C++ for your mobile device is here!";
                            NotificationCenter1->PresentNotification(myNotification);
                    }
                    __finally {
                            myNotification->DisposeOf();
                    }
            }
    
    }
    

Une fois votre application exécutée en appuyant sur F9, les éléments suivants s'affichent lorsque vous cliquez sur le bouton SetNumber :

  • Un badge sur l'icône d'application (sur l'écran d'accueil iOS) :
    IOSNotification.PNG

  • Un numéro auprès du message de notification dans le Centre de notifications (sur Android) :
    Android

Planifier les notifications

Vous pouvez aussi planifier les messages de notification en utilisant la méthode ScheduleNotification que la classe TNotificationCenter hérite de TCustomNotificationCenter.

Pour afficher un message de notification, vous devez créer une instance de la classe TNotification, puis définir les champs Name, AlertBody et FireDate.

  1. Déposez un nouveau TButton sur la fiche.
  2. Dans l'inspecteur d'objets, définissez la propriété Name sur ScheduleNotification.
  3. Créez l'événement OnClick du bouton ScheduleNotification en double-cliquant sur le bouton.
  4. Implémentez le gestionnaire d'événement pour l'événement OnClick du bouton ScheduleNotification en ajoutant le code suivant :
    • Pour Delphi :


    procedure TForm1.ScheduleNotificationClick(Sender: TObject);
    var
      MyNotification: TNotification;
    begin
      MyNotification&nbsp;:= NotificationCenter1.CreateNotification;
      try
        MyNotification.Name&nbsp;:= 'MyNotification';
        MyNotification.AlertBody&nbsp;:= 'Delphi for your mobile device is here!';
        // Fired in 10 seconds
        MyNotification.FireDate&nbsp;:= Now + EncodeTime(0, 0, 10, 0);
        // Send notification to the notification center
        NotificationCenter1.ScheduleNotification(MyNotification);
      finally
        MyNotification.DisposeOf;
      end;
    end;
    
    • Pour C++ :
    void __fastcall TForm1::ScheduleNotificationClick(TObject *Sender)
    {
            if (NotificationCenter1->Supported()) {
                    TNotification *myNotification = NotificationCenter1->CreateNotification();
                    __try {
                            myNotification->Name = "MyNotification";
                            myNotification->AlertBody = "C++ for your mobile device is here!";
                            // Fire in 10 seconds
                            myNotification->FireDate = Now() + EncodeTime(0, 0, 10, 0);
                            // Send notification to the notification center
                            NotificationCenter1->ScheduleNotification(myNotification);
                    }
                    __finally {
                            myNotification->DisposeOf();
                    }
    
            }
    }
    

Une fois votre application exécutée en appuyant sur F9, vous pouvez voir le message de notification AlertBody en haut de l'écran d'accueil de votre périphérique lorsque vous cliquez sur le bouton ScheduleNotification. Pour les périphériques iOS, ce message est similaire à l'écran suivant :

IOS7NotificationBanner.png

Répéter un message de notification

Vous pouvez également répéter un message de notification en utilisant la propriété RepeatInterval de l'objet TNotification.

Pour répéter un message de notification, vous devez créer une instance de la classe TNotification, puis définir les champs Name, AlertBody, et FireDate fields.

Vous devez également utiliser la méthode ScheduleNotification et définir la propriété RepeatInterval. Dans le code suivant, l'intervalle de répétition est défini à une minute.

  1. Déposez un nouveau TButton sur la fiche.
  2. Dans l'inspecteur d'objets, définissez la propriété Name sur RepeatedNotification.
  3. Créez l'événement OnClick du bouton RepeatedNotification en double-cliquant sur le bouton.
  4. Implémentez le gestionnaire d'événement pour l'événement OnClick du bouton RepeatedNotification en ajoutant le code suivant :
    • Pour Delphi :


    procedure TForm1.RepeatedNotificationClick(Sender: TObject);
    var
      MyNotification: TNotification;
    begin
      MyNotification&nbsp;:= NotificationCenter1.CreateNotification;
      try
        MyNotification.Title&nbsp;:= 'MyNotification';
        MyNotification.AlertBody&nbsp;:= 'Repeating notification each minute!';
        //Fired in 10 seconds
        MyNotification.FireDate&nbsp;:= Now + EncodeTime(0, 0, 10, 0);
        //Repeated each minute
        MyNotification.RepeatInterval&nbsp;:= TRepeatInterval.Minute;
        // Send notification to the notification center
        NotificationCenter1.ScheduleNotification(MyNotification);
      finally
        MyNotification.Free;
      end;
    end;
    
    • Pour C++ :
    void __fastcall TForm1::RepeatedNotificationClick(TObject *Sender) {
        if (NotificationCenter1->Supported()) {
            TNotification *myNotification =
                NotificationCenter1->CreateNotification();
            __try {
                myNotification->Name = "MyNotification";
                myNotification->AlertBody = "Repeating notification each minute!";
                // Fire in 10 seconds
                myNotification->FireDate = Now() + EncodeTime(0, 0, 10, 0);
                // Repeated each minute
                myNotification->RepeatInterval = TRepeatInterval::Minute;
                // Send notification to the notification center
                NotificationCenter1->ScheduleNotification(myNotification);
            }
            __finally {
                myNotification->Free();
            }
    
        }
    
    }
    

Une fois votre application exécutée en appuyant sur F9, vous pouvez voir le message de notification (AlertBody) en haut de l'écran d'accueil de votre périphérique lorsque vous cliquez sur le bouton RepeatedNotification. Pour les périphériques iOS, ce message est similaire à l'écran suivant :

IOS7RepeatedNotificationBannerCpp.png

Mettre à jour ou annuler un message de notification planifié ou répété

Chaque message de notification planifié est identifié par la propriété Name de l'objet TNotification.

Remarque : Pour la plate-forme iOS, CancelNotification et ScheduleNotification peuvent annuler ou mettre à jour les notifications qui n'ont pas encore été présentées.

Pour mettre à jour une notification planifiée, appelez simplement la méthode ScheduleNotification une nouvelle fois avec une instance de TNotificationCenter qui porte le même nom (propriété Name).

Pour annuler une notification planifiée, vous pouvez simplement appeler la méthode CancelNotification avec l'identificateur que vous avez utilisé.

  1. Déposez un nouveau TButton sur la fiche.
  2. Dans l'inspecteur d'objets, définissez la propriété Name sur CancelNotification.
  3. Créez l'événement OnClick du bouton CancelNotification en double-cliquant sur le bouton.
  4. Implémentez le gestionnaire d'événement pour l'événement OnClick du bouton CancelNotification en ajoutant le code suivant :
    • Pour Delphi :
    procedure TForm1.CancelNotificationClick(Sender: TObject);
    
    begin
       NotificationCenter1.CancelNotification('MyNotification');
    end;
    
    • Pour C++ :
      void __fastcall TForm1::CancelNotificationClick(TObject *Sender)
    {
       NotificationCenter1->CancelNotification("MyNotification");
    }
    

Présenter immédiatement le message de notification

Vous pouvez également afficher le message de notification immédiatement en utilisant la fonction PresentNotification.

Pour afficher un message de notification, vous devez créer une instance de la classe TNotification, puis définir les champs Name et AlertBody.

  1. Déposez un nouveau TButton sur la fiche.
  2. Dans l'inspecteur d'objets, définissez la propriété Name sur PresentNotification.
  3. Créez l'événement OnClick du bouton PresentNotification en double-cliquant sur le bouton.
  4. Implémentez le gestionnaire d'événement pour l'événement OnClick du bouton PresentNotification en ajoutant le code suivant :
    • Pour Delphi :


    procedure TForm1.PresentNotificationClick(Sender: TObject);
    var
      MyNotification: TNotification;
    begin
      MyNotification&nbsp;:= NotificationCenter1.CreateNotification;
      try
        MyNotification.Name&nbsp;:= 'MyNotification';
        MyNotification.AlertBody&nbsp;:= 'Delphi for your mobile device is here!';
        // Set Icon Badge Number (for iOS) or message number (for Android) as well
        MyNotification.Number&nbsp;:= 18;
        MyNotification.EnableSound&nbsp;:= False;
        // Send message to the notification center
        NotificationCenter1.PresentNotification(MyNotification);
      finally
        MyNotification.DisposeOf;
      end;
    end;
    
    • Pour C++ :
    void __fastcall TForm1::PresentNotificationClick(TObject *Sender)
    {
      if (NotificationCenter1->Supported()) {
               TNotification *myNotification = NotificationCenter1->CreateNotification();
               __try { 
                       myNotification->Name = "MyNotification";
                       myNotification->AlertBody = "C++ for your mobile device is here!";
                       // Set Icon Badge Number (for iOS) or message number (for Android) as well
                       myNotification->Number = 18;
                       myNotification->EnableSound = False;
                       // Send notification to the notification center
                       NotificationCenter1->PresentNotification(myNotification);
              }
              __finally {  
                       myNotification->DisposeOf();
              }
     }
     
    }
    

Personnalisation du son de notification

Vous pouvez utiliser un son personnalisé pour le message de notification immédiatement par le biais de la propriété SoundName de l'objet TNotification.

Vous devez créer une instance de la classe TNotification, et définir les propriétés EnableSound et SoundName. Vous devez également indiquer le chemin complet du fichier son et l'extension de fichier.

  1. Déposez un nouveau TButton sur la fiche.
  2. Dans l'inspecteur d'objets, définissez la propriété Name sur SoundNotification.
  3. Créez l'événement OnClick du bouton SoundNotification en double-cliquant sur le bouton.
  4. Implémentez le gestionnaire d'événement pour l'événement OnClick du bouton SoundNotification en ajoutant le code suivant :
    • Pour Delphi :


    procedure TForm1.SoundNotificationClick(Sender: TObject);
    var
      MyNotification: TNotification;
    begin
      MyNotification&nbsp;:= NotificationCenter1.CreateNotification;
      try
        MyNotification.Name&nbsp;:= 'MyNotification';
        MyNotification.AlertBody&nbsp;:= 'Delphi for your mobile device is here!';
        MyNotification.EnableSound&nbsp;:= True;
        MyNotification.SoundName&nbsp;:= GetSoundName;
        MyNotification.FireDate&nbsp;:= Now + EncodeTime(0, 0, 10, 0);
        // Send message to the notification center
        NotificationCenter1.ScheduleNotification(MyNotification);
      finally
        MyNotification.Free;
      end;
    end;
    
    • Pour C++ :
      • Dans le fichier .cpp, ajoutez le code suivant :
    void __fastcall TForm1::SoundNotificationClick(TObject *Sender)
    {
    TNotification *myNotification = NotificationCenter1->CreateNotification();
            __try {
                myNotification->Name = "MyNotification";
                myNotification->AlertBody = "C++ for your mobile device is here!";
                myNotification->EnableSound = true;
                myNotification->SoundName = GetSoundName();
                myNotification->FireDate = Now() + EncodeTime(0, 0, 10, 0);
                // Send notification to the notification center
               NotificationCenter1->ScheduleNotification(myNotification);
            }
            __finally {
                myNotification->Free();
            }
    }
    
  5. Déclarez la fonction GetSoundName.
    • Pour Delphi :
      • Définissez la déclaration GetSoundName dans la section private de l'unité.
      • Ajoutez System.IOUtils à la clause uses du projet.
    uses
      System.IOUtils;
    private
        function GetSoundName: string;
    
    • Pour C++ :
      • Dans le fichier d'en-tête (fichier .h), ajoutez la déclaration suivante :
      • Définissez la déclaration GetSoundName dans la section private de l'unité.
      • Incluez System.IOUtils.hpp à la clause uses du projet.
    #include <System.IOUtils.hpp>
    private:    // User declarations
         __fastcall  UnicodeString GetSoundName ();
    
  6. Implémentez la fonction GetSoundName.
    Remarque : Selon le système d'exploitation cible, les données de son doivent avoir une extension de fichier différente.
    • Pour Delphi :
    {$R *.fmx}
    function TForm1.GetSoundName: string;
    begin
    {$IFDEF IOS}
      Result := 'myiOSSound.caf';
    {$ENDIF}
    {$IFDEF ANDROID}
      Result := TPath.Combine(TPath.GetSharedDocumentsPath, 'myAndroidSound.mp3');
    {$ENDIF}
    end;
    
    • Pour C++ :
      • Dans le fichier .cpp, ajoutez le code suivant :
    UnicodeString __fastcall TForm1::GetSoundName ()
    {
        UnicodeString result;
    #if defined(_PLAT_IOS)
        result = "myiOSSound.caf";
    #endif
    #if defined(__ANDROID__)
        result = System::Ioutils::TPath::Combine(System::Ioutils::TPath::GetSharedDocumentsPath(), "myAndroidSound.mp3");
    #endif
        return result;
      //
    }
    
  7. Ajoutez les fichiers son à votre projet :
    • Recherchez les fichiers myAndroidSound.mp3 et myiOSSound.caf dans l'explorateur Windows, et déplacez-les dans le Gestionnaire de projets. Déposez-les sur le nom de votre projet.
      Remarque : Les fichiers son myAndroidSound.mp3 et myiOSSound.caf ne sont pas inclus dans l'installation de RAD Studio. Vous pouvez utiliser à la place les fichiers MP3 et CAF à votre disposition, mais n'oubliez pas de remplacer le nom dans l'extrait de code ci-dessus par le nom de vos fichiers. Voir ce lien pour plus d'informations sur la conversion de fichiers MP3 au format CAF : How to convert MP3 to CAF (EN)
    • Dans le dialogue de confirmation, cliquez sur Oui pour ajouter les fichiers son à votre projet.
  8. Ouvrez le Gestionnaire de déploiement pour vous assurer que les fichiers son sont déployés avec votre application. Vous pouvez voir les entrées correspondantes dans la colonne du chemin distant :
  9. Changez le chemin distant des fichiers ajoutés dans le Gestionnaire de déploiement :
    • Pour iOS : .\
    • Pour Android : assets\

Bannière de notification ou alerte de notification

Par défaut, votre application affiche la bannière de notification :

  • Bannière de notification sur l'iPad
    IOSNotificationBanner.PNG
  • Bannière de notification sur les périphériques Android
    Android
  • Alerte de notification (seulement pour les périphériques iOS)
    IOSNotificationAlert.PNG

Pour utiliser une alerte de notification plutôt qu'une bannière de notification (seulement pour les périphériques iOS), l'utilisateur final doit changer le style Alert en Alerts dans la page de configuration du Centre de notifications, disponible dans les paramètres du périphérique :

IOSNotificationCenterOption.PNG

Ajouter des actions à l'alerte de notification (iOS seulement)

Vous pouvez aussi personnaliser une alerte en ajoutant un bouton Action qui ouvre l'application.

Pour personnaliser une action d'alerte, vous devez définir le champ AlertAction sur le nom du bouton Action, puis définir le champ HasAction sur True, comme suit.

  1. Déposez un nouveau TButton sur la fiche.
  2. Dans l'inspecteur d'objets, définissez la propriété Name sur ActionNotification.
  3. Créez l'événement OnClick du bouton ActionNotification en double-cliquant sur le bouton.
  4. Implémentez le gestionnaire d'événement pour l'événement OnClick du bouton ActionNotification en ajoutant le code suivant :
    • Pour Delphi :


    procedure TForm1.ActionNotificationClick(Sender: TObject);
    var
      MyNotification: TNotification;
    begin
       MyNotification&nbsp;:= NotificationCenter1.CreateNotification;
      try
        MyNotification.Name&nbsp;:= 'MyNotification';
        MyNotification.AlertBody&nbsp;:= 'Delphi for iOS is here! ';
        MyNotification.Number&nbsp;:= 2;
        MyNotification.AlertAction&nbsp;:= 'Launch';
        MyNotification.HasAction&nbsp;:= True;
        MyNotification.FireDate&nbsp;:= Now + EncodeTime(0, 0, 20, 0);
        NotificationCenter1.ScheduleNotification(MyNotification);
      finally
        MyNotification.DisposeOf;
      end;
    end;
    
    • Pour C++ :
    void __fastcall TForm1::ActionNotificationClick(TObject *Sender)
    {
       if (NotificationCenter1->Supported()) {
               TNotification *myNotification = NotificationCenter1->CreateNotification();
               __try {
                       myNotification->Name = "MyNotification";
                       myNotification->AlertBody = "C++ for iOS is here!";
                       myNotification->Number = 2;
                       myNotification->AlertAction = "Launch";
                       myNotification->HasAction = True;
                       myNotification->FireDate = Now() + EncodeTime(0,0,20,0);
                       NotificationCenter1->ScheduleNotification(myNotification);
               }
               __finally {
                       myNotification->DisposeOf();
               }
       }
     }
    

Remarque : Seuls les périphériques iOS prennent en charge la fonctionnalité d'alerte de notification.

L'alerte de notification s'ouvre au moment spécifié via le champ FireDate.

IOSNotificationAlert.PNG

Ajouter une action aux notifications

La classe TNotificationCenter fournit le gestionnaire d'événement onReceiveLocalNotification qui vous permet d'écrire une réponse quand l'utilisateur clique sur le message de notification dans le centre de notifications. Pour écrire la réponse, double-cliquez sur le composant TNotificationCenter sur le Concepteur de fiches, puis implémentez le gestionnaire d'événement OnReceiveLocalNotification.

L'extrait de code suivant implémente une réponse pour afficher une zone de message indiquant "The <Notification name>" notification clicked."

  • Pour Delphi :
 procedure TForm1.NotificationCenter1ReceiveLocalNotification(Sender: TObject; ANotification: TNotification);
   begin
     ShowMessage('The ' + ANotification.Name + ' notification clicked.' );
   end;
  • Pour C++ :
void __fastcall TForm1::NotificationCenter1ReceiveLocalNotification(TObject *Sender, TNotification *ANotification)
{
       ShowMessage("The " + ANotification->Name + " notification clicked.");
}



MyNotification iOS.png

Exécution de l'application

Pour exécuter l'application, choisissez Exécuter > Exécuter ou appuyez sur F9. Cliquez sur les différents boutons pour planifier ou présenter des notifications sur votre périphérique.

Voir aussi

Exemples