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

# Notificaciones en vivo de Android

> Cree y actualice notificaciones dinámicas en tiempo real en dispositivos Android usando Notificaciones en vivo de OneSignal. Entregue contenido continuamente actualizado dentro de una sola notificación, simulando Live Activities de iOS para Android.

Las Notificaciones en vivo de Android de OneSignal le permiten enviar actualizaciones en tiempo real a una sola notificación, reduciendo el desorden y mejorando la participación. Estas notificaciones permanecen persistentes y actualizan su contenido dinámicamente, ideales para puntuaciones deportivas, progreso de descarga o seguimiento de eventos.

Para recibir Notificaciones en vivo, los usuarios de Android deben tener las notificaciones push habilitadas.

## Requisitos

* Su aplicación debe usar la última versión del [SDK de OneSignal](./mobile-sdk-setup).
* Los usuarios de Android deben tener los permisos de notificaciones push habilitados.

***

## Notificaciones en vivo vs. push estándar

A diferencia de las notificaciones push regulares, que envían una nueva notificación cada vez, las Notificaciones en vivo usan una sola notificación actualizada con el tiempo. Las actualizaciones se envían a través de la [API de creación de mensajes](/reference/create-message) usando el mismo `collapse_id`.

***

## Configuración

### 1. Implementar una extensión de servicio de notificación

Cree una clase `NotificationServiceExtension` que implemente `INotificationServiceExtension`. Esta clase intercepta las notificaciones entrantes y puede modificarlas o anularlas.

<Info>
  Consulte [Extensión de servicio de notificación de Android](./service-extensions#android-notification-service-extension) para más detalles.
</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)
            }
        }

        // Use `additional_data`to submit the Live Notification payload.
    		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. Agregar la extensión al Android Manifest

<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. Crear tipos de Notificación en vivo

Un Tipo de Notificación en vivo indica qué Notificación en vivo iniciar.

#### Definir claves

Las Notificaciones en vivo se referencian por una `key`, que determina cómo se enrutan las actualizaciones.

```kotlin NotificationServiceExtention.kt theme={null}
private const val PROGRESS_LIVE_NOTIFICATION = "progress"
```

#### Crear canales de notificación

Los canales definen cómo se comportan las notificaciones (sonido, vibración, apariencia). Debe crear canales para sus tipos de Notificación en vivo. Recomendamos:

* Importancia baja para notificaciones de progreso
* Deshabilitar insignias
* Mantener el sonido y la vibración al mínimo

Consulte [Categorías de canales de notificación de Android](./android-notification-categories) para más información.

#### Diseñar la Notificación en vivo

Al diseñar una Notificación en vivo, tiene la flexibilidad de crear un diseño de notificación para cada tipo de actualización. Cada diseño que cree debe asignarse a un tipo específico, lo que permite presentaciones variadas de una Notificación en vivo.

```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")
    }
```

**Consideraciones de diseño:**

* Ícono pequeño y color de acento
* Ícono grande
* Imagen grande
* Botones de acción

<Info>
  Consulte [Diseño de notificación personalizado de Android](https://developer.android.com/develop/ui/views/notifications/custom-notification) para opciones de diseño avanzadas.
</Info>

### 4. Extraer la carga útil de la Notificación en vivo

Las Notificaciones en vivo usan el campo `additional_data` para pasar contenido estructurado.

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

#### Esquema de Notificación en vivo

| Property           | Required | Description                                                                                                                                           |
| ------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`              | Yes      | Se usa para cargar la interfaz de usuario de notificación correcta.                                                                                   |
| `event`            | Yes      | La acción a realizar en la Notificación en vivo.                                                                                                      |
| `event_attributes` | No       | Los datos estáticos se usan para inicializar la Notificación en vivo; un esquema autodefinido que define los datos que su notificación necesita.      |
| `event_updates`    | No       | Contenido dinámico de la Notificación en vivo. Debe cumplir con la interfaz ContentState definida dentro de la Notificación en vivo de su aplicación. |

```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. Manejar eventos de Notificación en vivo

Cada Notificación en vivo debe responder a los siguientes eventos:

| Event    | Description                                                      | Required fields                     |
| -------- | ---------------------------------------------------------------- | ----------------------------------- |
| `start`  | Inicia una Notificación en vivo con datos estáticos y dinámicos. | `event_attributes`, `event_updates` |
| `update` | Actualiza la Notificación en vivo con nuevos datos dinámicos.    | `event_updates`                     |
| `end`    | Finaliza y elimina la Notificación en vivo.                      | None                                |

```kotlin NotificationServiceExtention.kt theme={null}
val liveNotificationEvent = liveNotificationPayload.optString("event", "")
```

***

## Iniciar una Notificación en vivo

Cuando esté listo para iniciar una Notificación en vivo:

* Establezca `event_attributes` para inicializar los datos estáticos de la Notificación en vivo. Estos datos no cambiarán durante la vida útil de la Notificación en vivo.
* Establezca datos de `event_updates` para inicializar los datos dinámicos de la Notificación en vivo. Estos son los datos que pueden y cambiarán durante la vida útil de la Notificación en vivo.
* Un [`collapse_id`](./push#collapse-id) para asegurarse de que cada actualización anule la anterior. Este ID debe ser único para la Notificación en vivo para garantizar que las actualizaciones posteriores se reflejen en la misma notificación.

```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"
  }'
```

***

## Actualizar Notificación en vivo

Puede actualizar la Notificación en vivo tantas veces como desee, siempre que se haya iniciado primero.

* Establezca datos de `event_updates` para inicializar los datos dinámicos de la Notificación en vivo. Estos son los datos que pueden y cambiarán durante la vida útil de la Notificación en vivo e informan con qué actualizar el contenido de su Notificación en vivo.

**Ejemplo de solicitud 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"
  }'
```

## Finalizar Notificación en vivo

**Ejemplo de solicitud 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>
  ¡Ha creado exitosamente una Notificación en vivo!

  Documentos relacionados:

  * [Extensión de servicio de notificación de Android](./service-extensions#android-notification-service-extension)
  * [Configuración del SDK de Android](./mobile-sdk-setup)
  * [API de creación de mensajes](/reference/create-message)
</Check>

***
