Passer au contenu principal
Les Notifications en direct Android de OneSignal vous permettent d’envoyer des mises à jour en temps réel vers une seule notification, réduisant l’encombrement et améliorant l’engagement. Ces notifications restent persistantes et mettent à jour leur contenu de manière dynamique—idéales pour les scores sportifs, la progression des téléchargements ou le suivi d’événements. Pour recevoir les Notifications en direct, les utilisateurs Android doivent avoir les notifications push activées.

Exigences

  • Votre application doit utiliser la dernière version du OneSignal SDK.
  • Les utilisateurs Android doivent avoir les autorisations de notification push activées.

Notifications en direct vs push standard

Contrairement aux notifications push classiques, qui envoient une nouvelle notification à chaque fois, les Notifications en direct utilisent une seule notification mise à jour au fil du temps. Les mises à jour sont envoyées via l’API Create Message en utilisant le même collapse_id.

Configuration

1. Implémenter une Extension de Service de Notification

Créez une classe NotificationServiceExtension qui implémente INotificationServiceExtension. Cette classe intercepte les notifications entrantes et peut les modifier ou les remplacer.
Consultez Extension de Service de Notification Android pour plus de détails.
NotificationServiceExtention.kt
package com.onesignal.sample.android

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import com.onesignal.notifications.INotificationReceivedEvent
import com.onesignal.notifications.INotificationServiceExtension
import org.json.JSONObject
import java.util.logging.Logger

class NotificationServiceExtension : INotificationServiceExtension {
  override fun onNotificationReceived(event: INotificationReceivedEvent) {
        val context = event.context
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager
            ?: run {
                logger.warning("NotificationManager not available.")
                return
            }

        notificationManager.let {
            if (!notificationChannelsCreated) {
                createNotificationChannels(notificationManager)
            }
        }

        // Utilisez `additional_data` pour soumettre la charge utile de Notification en direct.
    		val additionalData = event.notification.additionalData
        val liveNotificationPayload = additionalData?.optJSONObject("live_notification")
        if (liveNotificationPayload == null) {
            logger.info("No live notification payload found. Showing original notification.")
            return
        }

        event.preventDefault()
        handleLiveNotification(event, liveNotificationPayload, notificationManager, context)
    }
}

2. Ajouter l’extension au Manifest Android

  <meta-data android:name="com.onesignal.NotificationServiceExtension"
              android:value="com.onesignal.sample.android.NotificationServiceExtension" />

3. Créer des types de Notification en direct

Un Type de Notification en direct indique quelle Notification en direct démarrer.

Définir les clés

Les Notifications en direct sont référencées par une key, qui détermine comment les mises à jour sont acheminées.
NotificationServiceExtention.kt
private const val PROGRESS_LIVE_NOTIFICATION = "progress"

Créer des canaux de notification

Les canaux définissent le comportement des notifications (son, vibration, apparence). Vous devez créer des canaux pour vos types de Notification en direct. Nous recommandons :
  • Importance faible pour les notifications de progression
  • Désactiver les badges
  • Garder le son et la vibration au minimum
Consultez Catégories de canaux de notification Android pour plus d’informations.

Concevoir la Notification en direct

Lors de la conception d’une Notification en direct, vous avez la flexibilité de créer un design de notification pour chaque type de mise à jour. Chaque design que vous créez doit être assigné à un type spécifique, permettant des présentations variées d’une Notification en direct.
NotificationServiceExtention.kt
private fun updateProgressNotification(
        liveNotificationUpdates: JSONObject,
        context: Context,
        notificationManager: NotificationManager
    ) {
        val currentProgress = liveNotificationUpdates.optInt("current_progress", 0)

        val builder = NotificationCompat.Builder(context, PROGRESS_CHANNEL_ID)
            .setContentTitle("Progress Live Notifications")
            .setContentText("It's working...")
            .setSmallIcon(android.R.drawable.ic_media_play)
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, android.R.drawable.ic_dialog_info))
            .setOngoing(true)
            .setOnlyAlertOnce(true)
            .setProgress(100, currentProgress, false)
            .setAutoCancel(false) // Prevent auto-dismissal of notification until you set the end event

        notificationManager.notify(keyMap[PROGRESS_LIVE_NOTIFICATION]!!, builder.build())
        logger.info("Updated progress notification with progress: $currentProgress")
    }
Considérations de conception :
  • Petite icône & couleur d’accentuation
  • Grande icône
  • Grande image
  • Boutons d’action
Consultez Disposition de notification personnalisée Android pour des options de conception avancées.

4. Extraire la charge utile de Notification en direct

Les Notifications en direct utilisent le champ additional_data pour transmettre du contenu structuré.
NotificationServiceExtention.kt
val additionalData = event.notification.additionalData
val liveNotificationPayload = additionalData?.optJSONObject("live_notification")

Schéma de Notification en direct

PropriétéRequisDescription
keyOuiUtilisée pour charger l’interface utilisateur de notification correcte.
eventOuiL’action à effectuer sur la Notification en direct.
event_attributesNonLes données statiques sont utilisées pour initialiser la Notification en direct ; un schéma auto-défini qui définit les données nécessaires.
event_updatesNonContenu dynamique de la Notification en direct. Doit se conformer à l’interface ContentState définie dans la Notification en direct.
Example Live Notification Payload
  {
      "key": "celtics-vs-lakers",
      "event": "start",
      "event_attributes": {
          "homeTeam": "Celtics",
          "awayTeam": "Lakers",
          "game": "Finals Game 1"
      },
      "event_updates": {
          "quarter": 1,
          "homeScore": 0,
          "awayScore": 0,
      }
  }

5. Gérer les événements de Notification en direct

Chaque Notification en direct doit répondre aux événements suivants :
ÉvénementDescriptionChamps requis
startCommence une Notification en direct avec des données statiques et dynamiques.event_attributes, event_updates
updateMet à jour la Notification en direct avec de nouvelles données dynamiques.event_updates
endTermine et supprime la Notification en direct.Aucun
NotificationServiceExtention.kt
val liveNotificationEvent = liveNotificationPayload.optString("event", "")

Démarrer une Notification en direct

Lorsque vous êtes prêt à démarrer une Notification en direct :
  • Définissez event_attributes pour initialiser les données statiques de la Notification en direct. Ces données ne changeront pas pendant la durée de vie de la Notification en direct.
  • Définissez les données event_updates pour initialiser les données dynamiques de la Notification en direct. Ce sont les données qui peuvent et vont changer pendant la durée de vie de la Notification en direct.
  • Un collapse_id pour s’assurer que chaque mise à jour remplace la précédente. Cet ID doit être unique à la Notification en direct pour garantir que les mises à jour ultérieures sont reflétées dans la même notification.
curl
  curl -X "POST" "https://api.onesignal.com/notifications" \
       -H 'Authorization: key YOUR_REST_API_KEY' \
       -H 'Content-Type: application/json; charset=utf-8' \
       -d $'{
    "app_id": "YOUR_APP_ID",
    "isAndroid": true,
    "collapse_id": "THE_UNIQUE_ID_FOR_THIS_LIVE_NOTIFICATION",
    "data": {
      "live_notification": {
        "key": "progress",
        "event": "start",
        "event_attributes": {},
        "event_updates": {
          "current_progress": 0
        }
      }
    },
    "headings": {
      "en": "Start"
    },
    "contents": {
      "en": "Starting Live Notification"
    },
    "include_aliases": {
      "external_id": ["EID1", "EID2"]
    },
    "target_channel": "push"
  }'

Mettre à jour une Notification en direct

Vous pouvez mettre à jour la Notification en direct autant de fois que vous le souhaitez, tant qu’elle a été démarrée au préalable.
  • Définissez les données event_updates pour initialiser les données dynamiques de la Notification en direct. Ce sont les données qui peuvent et vont changer pendant la durée de vie de la Notification en direct et informent de quoi mettre à jour le contenu de votre Notification en direct.
Exemple de requête cURL
curl
  curl -X "POST" "https://api.onesignal.com/notifications" \
       -H 'Authorization: key YOUR_REST_API_KEY' \
       -H 'Content-Type: application/json; charset=utf-8' \
       -d $'{
    "app_id": "YOUR_APP_ID",
    "isAndroid": true,
    "collapse_id": "THE_UNIQUE_ID_FOR_THIS_LIVE_NOTIFICATION",
    "data": {
      "live_notification": {
        "key": "progress",
        "event": "update",
  			"event_attributes": {},
        "event_updates": {
          "current_progress": 80
        }
      }
    },
    "headings": {
      "en": "Update"
    },
    "contents": {
      "en": "Updating Live Notification"
    },
    "include_aliases": {
      "external_id": ["EID1", "EID2"]
    },
    "target_channel": "push"
  }'

Terminer une Notification en direct

Exemple de requête cURL
curl
  curl -X "POST" "https://api.onesignal.com/notifications" \
       -H 'Authorization: key YOUR_REST_API_KEY' \
       -H 'Content-Type: application/json; charset=utf-8' \
       -d $'{
    "app_id": "YOUR_APP_ID",
    "isAndroid": true,
    "collapse_id": "THE_UNIQUE_ID_FOR_THIS_LIVE_NOTIFICATION",
    "data": {
      "live_notification": {
        "key": "progress",
        "event": "dismiss"
      }
    },
    "headings": {
      "en": "Dismissing"
    },
    "contents": {
      "en": "Dismissing Live Notification"
    },
    "include_aliases": {
      "external_id": ["EID1", "EID2"]
    },
    "target_channel": "push"
  }'

Vous avez créé avec succès une Notification en direct !Documentation connexe :