> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Notifications en direct Android

> Créez et mettez à jour des notifications dynamiques en temps réel sur les appareils Android avec OneSignal Live Notifications. Diffusez du contenu continuellement mis à jour dans une seule notification, simulant les Live Activities iOS pour Android.

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](./mobile-sdk-setup).
* 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](/reference/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.

<Info>
  Consultez [Extension de Service de Notification Android](./service-extensions#android-notification-service-extension) pour plus de détails.
</Info>

```kotlin NotificationServiceExtention.kt theme={null}
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

<CodeGroup>
  ```xml AndroidManifest.xml theme={null}
    <meta-data android:name="com.onesignal.NotificationServiceExtension"
                android:value="com.onesignal.sample.android.NotificationServiceExtension" />
  ```

  ```xml Example AndroidManifest.xml theme={null}
  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools">

      <application
          android:allowBackup="true"
          android:dataExtractionRules="@xml/data_extraction_rules"
          android:fullBackupContent="@xml/backup_rules"
          android:icon="@mipmap/ic_launcher"
          android:name=".MainApplication"
          android:label="@string/app_name"
          android:roundIcon="@mipmap/ic_launcher_round"
          android:supportsRtl="true"
          android:theme="@style/Theme.OneSignalAndroidSample"
          tools:targetApi="31">
          <meta-data android:name="com.onesignal.NotificationServiceExtension"
              android:value="com.onesignal.sample.android.NotificationServiceExtension" />
          <activity
              android:name=".MainActivity"
              android:exported="true">
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />

                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>

  </manifest>
  ```
</CodeGroup>

### 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.

```kotlin NotificationServiceExtention.kt theme={null}
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](./android-notification-categories) 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.

```kotlin NotificationServiceExtention.kt theme={null}
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

<Info>
  Consultez [Disposition de notification personnalisée Android](https://developer.android.com/develop/ui/views/notifications/custom-notification) pour des options de conception avancées.
</Info>

### 4. Extraire la charge utile de Notification en direct

Les Notifications en direct utilisent le champ `additional_data` pour transmettre du contenu structuré.

```kotlin NotificationServiceExtention.kt theme={null}
val additionalData = event.notification.additionalData
val liveNotificationPayload = additionalData?.optJSONObject("live_notification")
```

#### Schéma de Notification en direct

| Propriété          | Requis | Description                                                                                                                                  |
| ------------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`              | Oui    | Utilisée pour charger l'interface utilisateur de notification correcte.                                                                      |
| `event`            | Oui    | L'action à effectuer sur la Notification en direct.                                                                                          |
| `event_attributes` | Non    | Les 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_updates`    | Non    | Contenu dynamique de la Notification en direct. Doit se conformer à l'interface ContentState définie dans la Notification en direct.         |

```json Example Live Notification Payload theme={null}
  {
      "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énement | Description                                                                   | Champs requis                       |
| --------- | ----------------------------------------------------------------------------- | ----------------------------------- |
| `start`   | Commence une Notification en direct avec des données statiques et dynamiques. | `event_attributes`, `event_updates` |
| `update`  | Met à jour la Notification en direct avec de nouvelles données dynamiques.    | `event_updates`                     |
| `end`     | Termine et supprime la Notification en direct.                                | Aucun                               |

```kotlin NotificationServiceExtention.kt theme={null}
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`](./push#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 theme={null}
  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 theme={null}
  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 theme={null}
  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"
  }'
```

***

<Check>
  Vous avez créé avec succès une Notification en direct !

  Documentation connexe :

  * [Extension de Service de Notification Android](./service-extensions#android-notification-service-extension)
  * [Configuration du SDK Android](./mobile-sdk-setup)
  * [API Create Message](/reference/create-message)
</Check>

***
