Créer une notification

Les notifications fournissent des informations courtes et opportunes sur les événements de votre application il n'est pas utilisé. Ce document explique comment créer une notification différentes fonctionnalités. Pour en savoir plus sur l'affichage des notifications sur Android, consultez la page Présentation des notifications. Pour obtenir un exemple de code utilisant des notifications, consultez la section Personnes exemple sur GitHub.

Le code de cette page utilise l'attribut NotificationCompat API de la bibliothèque AndroidX. Ces API vous permettent d'ajouter des fonctionnalités sur les versions plus récentes d'Android, tout en assurant la compatibilité avec Android. 9 (niveau d'API 28). Cependant, certaines fonctionnalités, telles que l'action de réponse intégrée, aboutit à une no-op sur les versions antérieures.

Ajouter la bibliothèque AndroidX Core

Bien que la plupart des projets créés avec Android Studio incluent les éléments dépendances pour utiliser NotificationCompat, vérifiez que vos dépendances au niveau du module build.gradle inclut la dépendance suivante:

Groovy

dependencies {
    implementation "androidx.core:core:2.2.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:2.2.0")
}

Créer une notification de base

Une notification dans son format le plus basique et le plus compact, également appelée réduit formulaire : affiche une icône, un titre et une petite quantité de texte. Ce montre comment créer une notification sur laquelle l'utilisateur peut appuyer pour lancer une l'activité dans votre application.

Figure 1 : Une notification avec une icône, un titre et du texte.

Pour plus de détails sur chaque partie d'une notification, consultez l'article À propos des notifications anatomie.

Déclarer l'autorisation d'exécution

Android 13 (niveau d'API 33) ou version ultérieure est compatible avec une autorisation d'exécution pour la publication des notifications non exemptées (y compris des services de premier plan) provenant d'une application.

L'autorisation que vous devez déclarer dans le fichier manifeste de votre application s'affiche dans l'extrait de code suivant:

<manifest ...>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <application ...>
        ...
    </application>
</manifest>

Pour en savoir plus sur les autorisations d'exécution, consultez Autorisation d'exécution des notifications.

Définir le contenu des notifications

Pour commencer, définissez le contenu et la chaîne de la notification à l'aide d'un NotificationCompat.Builder . L'exemple suivant montre comment créer une notification avec le paramètre suivantes:

  • Une petite icône, définie par setSmallIcon() Il s'agit du seul contenu visible par l'utilisateur qui est obligatoire.

  • Un titre, défini par setContentTitle()

  • Corps du texte, défini par setContentText()

  • La priorité de notification, définie par setPriority() La priorité détermine le degré d'intrusion de la notification sur Android 7.1 et plus tôt. Pour Android 8.0 et versions ultérieures, définissez plutôt l'importance du canal sur comme indiqué dans la section suivante.

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle(textTitle)
        .setContentText(textContent)
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

Le constructeur NotificationCompat.Builder nécessite que vous fournissiez un canal ID. Nécessaire pour la compatibilité avec Android 8.0 (niveau d'API 26) et mais il est ignoré par les versions antérieures.

Par défaut, le contenu textuel de la notification est tronqué pour tenir sur une ligne. Toi peut afficher des informations supplémentaires en créant une notification à développer.

Figure 2. Une annonce extensible dans sa forme réduite et développée.

Si vous souhaitez que la notification soit plus longue, vous pouvez activer une extension en ajoutant un modèle de style avec setStyle() Par exemple, le code suivant crée une zone de texte plus grande:

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Much longer text that cannot fit one line...")
        .setStyle(NotificationCompat.BigTextStyle()
                .bigText("Much longer text that cannot fit one line..."))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Much longer text that cannot fit one line...")
        .setStyle(new NotificationCompat.BigTextStyle()
                .bigText("Much longer text that cannot fit one line..."))
        .setPriority(NotificationCompat.PRIORITY_DEFAULT);

Pour en savoir plus sur d'autres styles de notifications de grande taille, y compris sur la façon d'ajouter les commandes de lecture d'images et de contenus multimédias, consultez la section Créer une annonce notification.

Créer un canal et définir son importance

Pour pouvoir envoyer la notification sur Android 8.0 ou version ultérieure, enregistrez votre canal de notification de l'application avec le en transmettant une instance de NotificationChannel jusqu'à createNotificationChannel(). Le code suivant est bloqué par une condition sur la Version de SDK_INT:

Kotlin

private fun createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is not in the Support Library.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = getString(R.string.channel_name)
        val descriptionText = getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system.
        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

Java

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is not in the Support Library.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this.
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

Parce que vous devez créer le canal de notification avant de publier des sur Android 8.0 et versions ultérieures, exécutez ce code dès que votre application démarre. Vous pouvez appeler cette méthode sans risque, car la création le canal de notification n'effectue aucune opération.

Le constructeur NotificationChannel nécessite un importance, en utilisant l'un des constantes du NotificationManager. Ce détermine comment interrompre l'utilisateur pour toute notification correspondante sur cette chaîne. Définissez la priorité sur setPriority() pour prendre en charge Android 7.1. et précédents, comme illustré dans l'exemple précédent.

Bien que vous deviez définir l'importance ou la priorité des notifications, comme indiqué dans le dans l'exemple suivant, le système ne garantit pas le comportement d'alerte que vous obtenez. Dans Dans certains cas, le système peut changer le niveau d'importance en fonction d'autres facteurs, et l'utilisateur peut toujours redéfinir le niveau d'importance canal.

Pour en savoir plus sur la signification des différents niveaux, consultez l'article importance des notifications niveaux.

Définir l'action tactile de la notification

Chaque notification doit répondre à un appui, généralement pour ouvrir une activité dans votre application correspondant à la notification. Pour ce faire, spécifiez un intent de contenu défini avec un élément PendingIntent et le transmettre à setContentIntent()

L'extrait de code suivant montre comment créer un intent de base pour ouvrir une activité Lorsque l'utilisateur appuie sur la notification:

Kotlin

// Create an explicit intent for an Activity in your app.
val intent = Intent(this, AlertDetails::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)

val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that fires when the user taps the notification.
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)

Java

// Create an explicit intent for an Activity in your app.
Intent intent = new Intent(this, AlertDetails.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that fires when the user taps the notification.
        .setContentIntent(pendingIntent)
        .setAutoCancel(true);

Ce code appelle setAutoCancel(), ce qui supprime automatiquement la notification lorsque l'utilisateur appuie dessus.

La méthode setFlags() comme illustré dans l'exemple précédent, préserve la navigation attendue de l'utilisateur. après avoir ouvert votre application à l'aide de la notification. Vous voudrez peut-être en fonction du type d'activité que vous démarrez, ce qui peut être les éléments suivants:

  • Activité qui existe exclusivement pour les réponses à la notification. Il n'y a aucune raison que l'utilisateur accède à cette activité lors d'une utilisation normale de l'application, Ainsi, l'activité commence une nouvelle tâche au lieu d'être ajoutée au tâche existante et retour pile. Il s'agit de la type d'intent créé dans l'exemple précédent.

  • Activité existante dans le flux d'application standard de votre application. Dans ce cas, le démarrage de l'activité crée une pile "Retour" afin que les attentes de l'utilisateur des boutons "Retour" et "Haut" sont préservées.

Pour en savoir plus sur les différentes façons de configurer l'intent de vos notifications, consultez Démarrer une activité à partir d'une notification

Afficher la notification

Pour afficher la notification, appelez NotificationManagerCompat.notify(), en lui transmettant un identifiant unique pour la notification. NotificationCompat.Builder.build() Ce processus est illustré dans l'exemple suivant :

Kotlin

with(NotificationManagerCompat.from(this)) {
    if (ActivityCompat.checkSelfPermission(
            this@MainActivity,
            Manifest.permission.POST_NOTIFICATIONS
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        // TODO: Consider calling
        // ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        // public fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
        //                                        grantResults: IntArray)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.

        return@with
    }
    // notificationId is a unique int for each notification that you must define.
    notify(NOTIFICATION_ID, builder.build())
}

Java

with(NotificationManagerCompat.from(this)) {
   if (ActivityCompat.checkSelfPermission(
           this@MainActivity,
           Manifest.permission.POST_NOTIFICATIONS
       ) != PackageManager.PERMISSION_GRANTED
   ) {
       // TODO: Consider calling
       // ActivityCompat#requestPermissions
       // here to request the missing permissions, and then overriding
       // public void onRequestPermissionsResult(int requestCode, String[] permissions,
       //                                        int[] grantResults)
       // to handle the case where the user grants the permission. See the documentation
       // for ActivityCompat#requestPermissions for more details.

       return
   }
   // notificationId is a unique int for each notification that you must define.
   notify(NOTIFICATION_ID, builder.build())
}

Enregistrez l'ID de notification que vous transmettez à NotificationManagerCompat.notify(). car vous en avez besoin lorsque vous souhaitez mettre à jour ou supprimer le notification.

De plus, afin de tester les notifications de base sur les appareils fonctionnant sur Android 13 ou version ultérieure, activez les notifications manuellement ou créez une boîte de dialogue pour les notifications de demande.

Ajouter des boutons d'action

Une notification peut proposer jusqu'à trois boutons d'action permettant à l'utilisateur de répondre. rapidement, par exemple pour répéter un rappel ou répondre à un SMS. Mais ces Les boutons d'action ne doivent pas reproduire l'action effectuée lorsque l'utilisateur appuie sur l' notification.

Figure 3. Une notification avec un bouton d'action.

Pour ajouter un bouton d'action, transmettez un PendingIntent à la addAction() . Cela s'apparente à la configuration de l'action tactile par défaut des notifications, à l'exception au lieu de lancer une activité, vous pouvez effectuer d'autres tâches, comme démarrer une BroadcastReceiver qui exécute une tâche en arrière-plan afin que l'action n'interrompe pas l'application. qui est déjà ouvert.

Par exemple, le code suivant montre comment envoyer une diffusion à une audience destinataire:

Kotlin

val ACTION_SNOOZE = "snooze"

val snoozeIntent = Intent(this, MyBroadcastReceiver::class.java).apply {
    action = ACTION_SNOOZE
    putExtra(EXTRA_NOTIFICATION_ID, 0)
}
val snoozePendingIntent: PendingIntent =
    PendingIntent.getBroadcast(this, 0, snoozeIntent, 0)</span>
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent)

Java

String ACTION_SNOOZE = "snooze"

Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
        PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);</span>

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setContentIntent(pendingIntent)
        .addAction(R.drawable.ic_snooze, getString(R.string.snooze),
                snoozePendingIntent);

Pour en savoir plus sur la création d'un BroadcastReceiver afin qu'il s'exécute en arrière-plan consultez la présentation des diffusions.

Si vous essayez de créer une notification avec des boutons de lecture multimédia, par exemple pour mettre en pause ou passer des pistes, consultez Créer une notification pour les contenus multimédias de commande.

Ajouter une action de réponse directe

L'action de réponse directe, introduite dans Android 7.0 (niveau d'API 24), permet aux utilisateurs saisissez du texte directement dans la notification. Le texte est ensuite envoyé à votre sans ouvrir d'activité. Par exemple, vous pouvez utiliser une action de réponse directe pour permettre aux utilisateurs de répondre à des SMS ou de mettre à jour des listes de tâches depuis le .

Figure 4. Appuyez sur "Répondre". permet d'ouvrir le champ de saisie de texte.

L'action de réponse directe s'affiche sous la forme d'un bouton supplémentaire dans la notification. ouvre une zone de saisie de texte. Le système joint le texte à la fin de la saisie à l'intent que vous spécifiez pour l'action de notification et envoie le pour votre application.

Ajouter le bouton "Répondre"

Pour créer une action de notification compatible avec les réponses directes, procédez comme suit:

  1. Créer une instance de RemoteInput.Builder que vous pouvez ajouter à votre action de notification. Le constructeur de cette classe accepte une chaîne que le système utilise comme clé pour la saisie de texte. Votre appli plus tard utilise cette clé pour récupérer le texte de l'entrée.

    Kotlin

      // Key for the string that's delivered in the action's intent.
      private val KEY_TEXT_REPLY = "key_text_reply"
      var replyLabel: String = resources.getString(R.string.reply_label)
      var remoteInput: RemoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).run {
          setLabel(replyLabel)
          build()
      }
      

    Java

      // Key for the string that's delivered in the action's intent.
      private static final String KEY_TEXT_REPLY = "key_text_reply";
    
      String replyLabel = getResources().getString(R.string.reply_label);
      RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
              .setLabel(replyLabel)
              .build();
      
  2. Créez un PendingIntent pour l'action "Répondre".

    Kotlin

      // Build a PendingIntent for the reply action to trigger.
      var replyPendingIntent: PendingIntent =
          PendingIntent.getBroadcast(applicationContext,
              conversation.getConversationId(),
              getMessageReplyIntent(conversation.getConversationId()),
              PendingIntent.FLAG_UPDATE_CURRENT)
      

    Java

      // Build a PendingIntent for the reply action to trigger.
      PendingIntent replyPendingIntent =
              PendingIntent.getBroadcast(getApplicationContext(),
                      conversation.getConversationId(),
                      getMessageReplyIntent(conversation.getConversationId()),
                      PendingIntent.FLAG_UPDATE_CURRENT);
      
    <ph type="x-smartling-placeholder">
  3. Fixez le RemoteInput à une action en utilisant addRemoteInput()

    Kotlin

      // Create the reply action and add the remote input.
      var action: NotificationCompat.Action =
          NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
              getString(R.string.label), replyPendingIntent)
              .addRemoteInput(remoteInput)
              .build()
      

    Java

      // Create the reply action and add the remote input.
      NotificationCompat.Action action =
              new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon,
                      getString(R.string.label), replyPendingIntent)
                      .addRemoteInput(remoteInput)
                      .build();
      
  4. Appliquez l'action à une notification et émettez la notification.

    Kotlin

      // Build the notification and add the action.
      val newMessageNotification = Notification.Builder(context, CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_message)
              .setContentTitle(getString(R.string.title))
              .setContentText(getString(R.string.content))
              .addAction(action)
              .build()
    
      // Issue the notification.
      with(NotificationManagerCompat.from(this)) {
          notificationManager.notify(notificationId, newMessageNotification)
      }
      

    Java

      // Build the notification and add the action.
      Notification newMessageNotification = new Notification.Builder(context, CHANNEL_ID)
              .setSmallIcon(R.drawable.ic_message)
              .setContentTitle(getString(R.string.title))
              .setContentText(getString(R.string.content))
              .addAction(action)
              .build();
    
      // Issue the notification.
      NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
      notificationManager.notify(notificationId, newMessageNotification);
      

Le système invite l'utilisateur à saisir une réponse lorsqu'il déclenche l'événement action de notification, comme illustré dans la figure 4.

Récupérer les entrées utilisateur à partir de la réponse

Pour recevoir les entrées utilisateur à partir de l'interface de réponse de la notification, appelez RemoteInput.getResultsFromIntent(), en transmettant le Intent reçu par votre BroadcastReceiver:

Kotlin

private fun getMessageText(intent: Intent): CharSequence? {
    return RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_TEXT_REPLY)
}

Java

private CharSequence getMessageText(Intent intent) {
    Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
    if (remoteInput != null) {
        return remoteInput.getCharSequence(KEY_TEXT_REPLY);
    }
    return null;
 }

Après avoir traité le texte, mettez à jour la notification en appelant NotificationManagerCompat.notify() avec le même ID et la même balise, le cas échéant. C'est nécessaire pour masquer l'interface de réponse directe et confirmer à l'utilisateur que sa réponse est bien reçu et traité.

Kotlin

// Build a new notification, which informs the user that the system
// handled their interaction with the previous notification.
val repliedNotification = Notification.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_message)
        .setContentText(getString(R.string.replied))
        .build()

// Issue the new notification.
NotificationManagerCompat.from(this).apply {
    notificationManager.notify(notificationId, repliedNotification)
}

Java

// Build a new notification, which informs the user that the system
// handled their interaction with the previous notification.
Notification repliedNotification = new Notification.Builder(context, CHANNEL_ID)
        .setSmallIcon(R.drawable.ic_message)
        .setContentText(getString(R.string.replied))
        .build();

// Issue the new notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, repliedNotification);

Lorsque vous travaillez avec cette nouvelle notification, utilisez le contexte transmis à la récepteur onReceive() .

Ajoutez la réponse au bas de la notification en appelant setRemoteInputHistory() Toutefois, si vous développez une application de chat, créez un style notification et ajoutez le paramètre nouveau message dans la conversation.

Pour obtenir d'autres conseils sur les notifications d'une application de chat, consultez la section bonnes pratiques concernant les applications de chat.

Ajouter une barre de progression

Les notifications peuvent inclure un indicateur de progression animé qui montre aux utilisateurs l'état d'une opération en cours.

Figure 5. La barre de progression une opération.

Si vous pouvez à tout moment estimer l'étendue de l'opération, utilisez la "déterminer" de l'indicateur, comme illustré dans la figure 5, en appelant setProgress(max, progress, false) Le premier paramètre correspond à la requête , telle que 100. Le deuxième est dans quelle mesure est terminé. Le dernier indique qu'il s'agit d'un progrès déterminé sur la barre d'adresse.

Au fur et à mesure que l'opération se poursuit, appelez en permanence setProgress(max, progress, false) avec une valeur mise à jour pour progress et envoyez à nouveau la notification, car comme illustré dans l'exemple suivant.

Kotlin

val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply {
    setContentTitle("Picture Download")
    setContentText("Download in progress")
    setSmallIcon(R.drawable.ic_notification)
    setPriority(NotificationCompat.PRIORITY_LOW)
}
val PROGRESS_MAX = 100
val PROGRESS_CURRENT = 0
NotificationManagerCompat.from(this).apply {
    // Issue the initial notification with zero progress.
    builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
    notify(notificationId, builder.build())

    // Do the job that tracks the progress here.
    // Usually, this is in a worker thread.
    // To show progress, update PROGRESS_CURRENT and update the notification with:
    // builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
    // notificationManager.notify(notificationId, builder.build());

    // When done, update the notification once more to remove the progress bar.
    builder.setContentText("Download complete")
            .setProgress(0, 0, false)
    notify(notificationId, builder.build())
}

Java

...
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID);
builder.setContentTitle("Picture Download")
        .setContentText("Download in progress")
        .setSmallIcon(R.drawable.ic_notification)
        .setPriority(NotificationCompat.PRIORITY_LOW);

// Issue the initial notification with zero progress.
int PROGRESS_MAX = 100;
int PROGRESS_CURRENT = 0;
builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
notificationManager.notify(notificationId, builder.build());

// Do the job that tracks the progress here.
// Usually, this is in a worker thread.
// To show progress, update PROGRESS_CURRENT and update the notification with:
// builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false);
// notificationManager.notify(notificationId, builder.build());

// When done, update the notification once more to remove the progress bar.
builder.setContentText("Download complete")
        .setProgress(0,0,false);
notificationManager.notify(notificationId, builder.build());

À la fin de l'opération, progress doit être égal à max. Vous pouvez quitter barre de progression pour indiquer que l'opération est terminée ou la supprimer. Dans les deux cas, Mettez à jour le texte de la notification pour indiquer que l'opération est terminée. Pour supprimer la barre de progression, appelez setProgress(0, 0, false).

Pour afficher une barre de progression indéterminée (une barre qui n'indique pas l'achèvement pourcentage), appelez setProgress(0, 0, true). Le résultat est un indicateur qui a le même style que la barre de progression précédente, sauf qu'il s'agit qui n'indique pas l'achèvement. L'animation de progression est exécutée jusqu'au appelez setProgress(0, 0, false), puis mettez à jour la notification pour supprimer l'indicateur d'activité.

N'oubliez pas de modifier le texte de la notification pour indiquer que l'opération terminé.

Définir une catégorie à l'échelle du système

Android utilise des catégories prédéfinies à l'échelle du système pour déterminer s'il faut déranger l'utilisateur avec une notification donnée lorsqu'il active le mode Ne pas déranger mode.

Si votre notification appartient à l'une des catégories définies dans l'article NotificationCompat, comme CATEGORY_ALARM, CATEGORY_REMINDER, CATEGORY_EVENT ou CATEGORY_CALL : déclaration en lui transmettant la catégorie appropriée setCategory():

Kotlin

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE)

Java

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE);

Le système utilise ces informations sur votre catégorie de notifications décisions concernant l'affichage de votre notification lorsque l'appareil est en mode Ne pas déranger. Cependant, vous n'êtes pas obligé de définir une catégorie à l'échelle du système. Uniquement si vos notifications correspondent à l'une des catégories définies dans NotificationCompat

Afficher un message urgent

Votre application peut avoir besoin d'afficher un message urgent et urgent, comme un un appel téléphonique entrant ou une alarme qui sonne. Dans ces situations, vous pouvez associer intent plein écran avec votre notification.

Lorsque la notification est appelée, les utilisateurs voient l'un des éléments suivants, en fonction état de verrouillage de l'appareil:

  • Si l'appareil de l'utilisateur est verrouillé, une activité en plein écran s'affiche et recouvre l'écran de verrouillage.
  • Si l'appareil de l'utilisateur est déverrouillé, la notification apparaît dans une vue développée contenant des options pour gérer ou ignorer la notification.

L'extrait de code suivant montre comment associer votre notification à intent plein écran:

Kotlin

val fullScreenIntent = Intent(this, ImportantActivity::class.java)
val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
    fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)

var builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setFullScreenIntent(fullScreenPendingIntent, true)

Java

Intent fullScreenIntent = new Intent(this, ImportantActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
        fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        .setFullScreenIntent(fullScreenPendingIntent, true);

Définir la visibilité de l'écran de verrouillage

Pour contrôler le niveau de détail visible dans la notification depuis l'écran de verrouillage, procédez comme suit : appel setVisibility() et spécifiez l'une des valeurs suivantes:

  • VISIBILITY_PUBLIC: tout le contenu de la notification s'affiche sur l'écran de verrouillage.

  • VISIBILITY_SECRET: aucune partie de la notification ne s'affiche sur l'écran de verrouillage.

  • VISIBILITY_PRIVATE: que des informations de base, telles que l'icône de la notification et le contenu s'affiche sur l'écran de verrouillage. L'intégralité du contenu de la notification afficher.

Lorsque vous définissez VISIBILITY_PRIVATE, vous pouvez également fournir une autre version de le contenu de la notification qui masque certains détails. Par exemple, une application de SMS peut afficher la notification "Vous avez 3 nouveaux SMS", mais masque le contenu et les expéditeurs du message. Pour fournir cette alternative notification, créez d'abord la notification alternative avec NotificationCompat.Builder comme d'habitude. Joignez ensuite la notification alternative à la notification normale avec setPublicVersion()

Gardez à l'esprit que l'utilisateur a toujours le contrôle absolu sur le fait que son notifications sont visibles sur l'écran de verrouillage et peuvent les contrôler en fonction canaux de notification de l'application.

Modifier une notification

Pour modifier une notification après l'avoir envoyée, appelez NotificationManagerCompat.notify() à nouveau, en transmettant l'ID que vous avez utilisé auparavant. Si la notification précédente est ignorée, une nouvelle notification est créée à la place.

Vous pouvez appeler setOnlyAlertOnce() La notification interrompt l'utilisateur (avec un son, une vibration ou une image ou des indices : uniquement la première fois que la notification s'affiche, et non plus tard. mises à jour.

Supprimer une notification

Les notifications restent visibles jusqu'à ce que l'une des situations suivantes se produise:

  • L'utilisateur ignore la notification.
  • L'utilisateur appuie sur la notification, si vous appelez setAutoCancel() lorsque vous créer la notification.
  • Vous appelez cancel() pour un ID de notification spécifique. Cette méthode supprime aussi les cours les notifications.
  • Vous appelez cancelAll(), ce qui supprime toutes les notifications envoyées précédemment.
  • La durée spécifiée est écoulée si vous définissez un délai d'inactivité lors de la création de en utilisant setTimeoutAfter() Si nécessaire, vous pouvez annuler une notification avant le délai spécifié. est écoulée.

Bonnes pratiques pour les applications de chat

Tenez compte des bonnes pratiques listées ici lorsque vous créez des notifications pour votre de messagerie et de chat.

Utiliser MessagingStyle

À partir d'Android 7.0 (niveau d'API 24), Android fournit un style de notification. spécialement conçu pour le contenu des messages. Avec les NotificationCompat.MessagingStyle vous pouvez modifier plusieurs libellés affichés dans la notification, y compris le titre de la conversation, les messages supplémentaires et l'affichage du contenu la notification.

L'extrait de code suivant montre comment personnaliser le style d'une notification. à l'aide de la classe MessagingStyle.

Kotlin

val user = Person.Builder()
    .setIcon(userIcon)
    .setName(userName)
    .build()

val notification = NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("2 new messages with $sender")
    .setContentText(subject)
    .setSmallIcon(R.drawable.new_message)
    .setStyle(NotificationCompat.MessagingStyle(user)
        .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson())
        .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson())
    )
    .build()

Java

Person user = new Person.Builder()
    .setIcon(userIcon)
    .setName(userName)
    .build();

Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("2 new messages with " + sender)
    .setContentText(subject)
    .setSmallIcon(R.drawable.new_message)
    .setStyle(new NotificationCompat.MessagingStyle(user)
        .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson())
        .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson())
    )
    .build();

À partir d'Android 9.0 (niveau d'API 28), vous devez également utiliser la classe la classe Person afin d'obtenir un rendu optimal de la notification et de ses avatars.

Lorsque vous utilisez NotificationCompat.MessagingStyle, procédez comme suit:

  • Appeler MessagingStyle.setConversationTitle() pour donner un titre aux chats de groupe de plus de deux personnes. Un bon le titre de la conversation peut être le nom du chat de groupe, avoir un nom, une liste des participants à la conversation. Sans cela, le message peut être considéré comme appartenant à une conversation en tête-à-tête avec l'expéditeur du message le plus récent de la conversation.
  • Utilisez les MessagingStyle.setData() permettant d'inclure des messages multimédias tels que des images. Types MIME du format image/* sont pris en charge.

Utiliser la réponse directe

Elle permet à un utilisateur de répondre de manière intégrée à un message.

  • Lorsqu'un utilisateur répond par une action de réponse intégrée, utilisez MessagingStyle.addMessage() pour mettre à jour la notification MessagingStyle, sans retirer ni annuler la . Si vous n'annulez pas la notification, l'utilisateur peut en envoyer plusieurs réponses à partir de la notification.
  • Pour rendre l'action de réponse intégrée compatible avec Wear OS, appelez Action.WearableExtender.setHintDisplayInlineAction(true)
  • Utilisez les addHistoricMessage() pour contextualiser une conversation en ajoutant des données historiques messages à la notification.

Activer la fonctionnalité Réponse suggérée

  • Pour activer Réponse suggérée, appelez setAllowGeneratedResponses(true) sur l'action "Répondre". Les réponses suggérées seront alors disponibles pour les utilisateurs lorsque la notification est pontée vers un appareil Wear OS. Réponse suggérée les réponses sont générées par un modèle de machine learning entièrement opérationnel le contexte fourni par NotificationCompat.MessagingStyle. notification, et aucune donnée n'est importée sur Internet pour générer des réponses.

Ajouter des métadonnées de notification