Cómo crear una notificación

Las notificaciones brindan información breve y oportuna sobre eventos en tu app no está en uso. En este documento, se muestra cómo crear una notificación con varias funciones. Para ver una introducción sobre cómo aparecen las notificaciones en Android, consulta la Descripción general de notificaciones. Para ver un código de muestra en el que se usan notificaciones, consulta el artículo Personas muestra en GitHub.

El código de esta página utiliza el NotificationCompat APIs de la biblioteca de AndroidX. Estas APIs te permiten agregar funciones que solo están disponibles en versiones más recientes de Android y, al mismo tiempo, brindar compatibilidad con Android 9 (nivel de API 28). Sin embargo, algunas funciones, como la acción de respuesta en línea el resultado es una no-op en versiones anteriores.

Cómo agregar la biblioteca de AndroidX Core

Si bien la mayoría de los proyectos creados con Android Studio incluyen las dependencias para usar NotificationCompat, verifica que tu archivo El archivo build.gradle incluye la siguiente dependencia:

Groovy

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

Kotlin

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

Cómo crear una notificación básica

Notificación en su forma más básica y compacta, también conocida como contraída formulario, muestra un ícono, un título y una pequeña cantidad de contenido de texto. Esta en la que se muestra cómo crear una notificación que el usuario pueda presionar para iniciar una la actividad en tu app.

Figura 1: Una notificación con un icono, un título y algo de texto.

Para obtener más detalles sobre cada parte de una notificación, lee acerca de las notificaciones anatomía.

Declara el permiso de tiempo de ejecución

Android 13 (nivel de API 33) y las versiones posteriores admiten un permiso de tiempo de ejecución para publicar notificaciones no exentas (incluidos los servicios en primer plano [FGS]) de una aplicación

El permiso que debes declarar en el archivo de manifiesto de tu app aparece en el siguiente fragmento de código:

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

Para obtener más información sobre los permisos de tiempo de ejecución, consulta Permiso de tiempo de ejecución de notificaciones.

Cómo definir el contenido de la notificación

Para comenzar, configura el contenido y el canal de la notificación con un NotificationCompat.Builder . En el siguiente ejemplo, se muestra cómo crear una notificación con la lo siguiente:

  • Un pequeño ícono, establecido por setSmallIcon() que es el único contenido necesario visible para el usuario

  • Un título, establecido por setContentTitle()

  • El texto del cuerpo, establecido por setContentText()

  • La prioridad de la notificación, establecida por setPriority() La prioridad determina cuán intrusiva es la notificación en Android 7.1 y anteriormente. Para Android 8.0 y versiones posteriores, establece la importancia del canal en se muestra en la siguiente sección.

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);

El constructor NotificationCompat.Builder requiere que proporciones un canal ID. Esto es necesario para brindar compatibilidad con Android 8.0 (nivel de API 26) y pero que las versiones anteriores ignoran.

De forma predeterminada, el contenido de texto de la notificación se trunca para que quepa en una línea. Tú puede mostrar información adicional creando una notificación expandible.

Figura 2: Un anuncio expandible en su forma contraída y expandida.

Si deseas que la notificación sea más larga, puedes habilitar una notificación una notificación agregando una plantilla de estilo con setStyle() Por ejemplo, el siguiente código crea un área de texto más 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);

Para obtener más información sobre otros estilos de notificaciones grandes, incluido cómo agregar una imagen y controles de reproducción multimedia, consulte Cómo crear un anuncio notificación.

Cómo crear un canal y definir la importancia

Para poder entregar la notificación en Android 8.0 y versiones posteriores, registra tu canal de notificaciones de tu app con el sistema pasando una instancia de NotificationChannel para createNotificationChannel(). El siguiente código está bloqueado por una condición en la Versión 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);
    }
}

Porque debes crear el canal de notificaciones antes de publicar cualquier en Android 8.0 y versiones posteriores, ejecuta este código tan pronto como tu app comienza el ciclo de vida. Se puede llamar a este método varias veces, ya que crear un mensaje el canal de notificaciones no realiza ninguna operación.

El constructor NotificationChannel requiere un importance, con uno de los constantes de la clase NotificationManager. Esta determina cómo interrumpir al usuario con cualquier notificación a este canal. Establece la prioridad con setPriority() para admitir Android 7.1. y anteriores, como se muestra en el ejemplo anterior.

Si bien debes definir la importancia o la prioridad de la notificación como se muestra en el siguiente, el sistema no garantiza el comportamiento de alerta que obtendrás. En en algunos casos, el sistema puede cambiar el nivel de importancia según otros factores y el usuario siempre puede redefinir el nivel de importancia de un canal.

Para obtener más información sobre el significado de los diferentes niveles, lee lo siguiente: importancia de las notificaciones niveles.

Cómo establecer la acción de toque de la notificación

Cada notificación debe responder a un toque, generalmente para abrir una actividad en tu app correspondiente a la notificación. Para hacerlo, especifica un intent de contenido definido con un PendingIntent objeto y se lo pasa al setContentIntent()

En el siguiente fragmento, se muestra cómo crear un intent básico para abrir una actividad cuando el usuario presiona la notificación:

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);

Este código llama setAutoCancel(): que quita automáticamente la notificación cuando el usuario la presiona.

Método setFlags() que se muestra en el ejemplo anterior, conserva la navegación esperada del usuario una vez que el usuario abra la app desde la notificación. Es posible que quieras según el tipo de actividad que estés iniciando, que puede ser una de lo siguiente:

  • Una actividad que existe exclusivamente para respuestas a la notificación. No hay motivo para que el usuario navegue a esta actividad durante el uso normal de la app. por lo que la actividad inicia una nueva tarea en lugar de agregarse a la lista la tarea existente y volver de la API. Este es el tipo de intent creado en el ejemplo anterior.

  • Una actividad que existe en el flujo regular de la app. En este caso, iniciar la actividad crea una pila de actividades para que las expectativas del usuario para los botones Atrás y Arriba son y cómo se preservan.

Para obtener más información sobre las diferentes formas de configurar el intent de tu notificación, consulta Cómo iniciar una actividad desde una notificación

Cómo mostrar la notificación

Para que aparezca la notificación, llama NotificationManagerCompat.notify(): un ID único para la notificación y el resultado NotificationCompat.Builder.build() Esto se muestra en el siguiente ejemplo:

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())
}

Guarda el ID de la notificación que pasas a NotificationManagerCompat.notify(). porque lo necesitas para actualizar o quitar notificación.

Además, con el fin de probar las notificaciones básicas en los dispositivos que ejecutan En Android 13 y versiones posteriores, activa las notificaciones manualmente o crea un diálogo para solicitar notificaciones.

Cómo agregar botones de acción

Una notificación puede ofrecer hasta tres botones de acción que permitan al usuario responder de forma rápida, como para posponer un recordatorio o responder un mensaje de texto. Pero estos los botones de acción no deben duplicar la acción realizada cuando el usuario toca el notificación.

Figura 3: Una notificación con un botón de acción.

Para agregar un botón de acción, pasa un PendingIntent al addAction() . Esto es como configurar la acción de toque predeterminada de la notificación, excepto en lugar de iniciar una actividad, puedes hacer otras cosas, como iniciar un BroadcastReceiver que realiza una tarea en segundo plano para que la acción no interrumpa a la app que ya está abierto.

Por ejemplo, el siguiente código muestra cómo enviar una transmisión a una dirección receptor:

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);

Obtén más información para compilar un BroadcastReceiver de modo que se ejecute en segundo plano consulta la Descripción general de las transmisiones.

Si, en cambio, quieres crear una notificación con botones de reproducción multimedia, como para pausar y omitir pistas, consulta cómo crear una notificación con controles de acceso.

Cómo agregar una acción de respuesta directa

La acción de respuesta directa, que se introdujo en Android 7.0 (nivel de API 24), les permite a los usuarios ingresar texto directamente en la notificación. Luego, el texto se envía a tu app sin abrir una actividad. Por ejemplo, puedes usar una acción de respuesta directa para permitir que los usuarios respondan mensajes de texto o actualicen las listas de tareas desde el notificación.

Figura 4: Presionar la opción "Responder" abre la entrada de texto.

La acción de respuesta directa aparece como un botón adicional en la notificación que indica que abre una entrada de texto. Cuando el usuario termina de escribir, el sistema adjunta el texto respuesta al intent que especificas para la acción de notificación y envía el a tu app.

Cómo agregar el botón de respuesta

Para crear una acción de notificación que admita la respuesta directa, sigue estos pasos:

  1. Crea una instancia de RemoteInput.Builder que puedes agregar a tu acción de notificación. El constructor de esta clase acepta una cadena que el sistema usa como clave para la entrada de texto. Tu app más tarde usa esa tecla para recuperar el texto de la entrada.

    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. Crea un PendingIntent para la acción de respuesta.

    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);
      
  3. Adjunta el archivo RemoteInput objeto a una acción con 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. Aplica la acción a una notificación y emite la notificación.

    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);
      

El sistema le pide al usuario que ingrese una respuesta cuando active la de notificación, como se muestra en la figura 4.

Cómo recuperar entradas del usuario a partir de la respuesta

Para recibir entradas del usuario desde la IU de respuesta de la notificación, llama RemoteInput.getResultsFromIntent(): y pásale el elemento Intent que recibió tu BroadcastReceiver, de la siguiente manera:

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;
 }

Después de procesar el mensaje de texto, llama a una llamada para actualizar la notificación NotificationManagerCompat.notify() con el mismo ID y la misma etiqueta, si se usan Este es necesario para ocultar la interfaz de usuario de respuesta directa y confirmar al usuario que su respuesta se recibe y procesa correctamente.

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);

Cuando trabajes con esta nueva notificación, usa el contexto que se pasa al del receptor onReceive() .

Llama para adjuntar la respuesta en la parte inferior de la notificación setRemoteInputHistory() Sin embargo, si estás compilando una app de mensajería, crea un estilo de mensajería notificación y adjunta el nuevo mensaje a la conversación.

Para obtener más consejos sobre las notificaciones de una app de mensajería, consulta la sección sobre prácticas recomendadas para las apps de mensajería.

Cómo agregar una barra de progreso

Las notificaciones pueden incluir un indicador de progreso animado que muestre a los usuarios la estado de una operación en curso.

Figura 5: La barra de progreso durante una operación.

Si puedes estimar qué parte de la operación estará completa en cualquier momento, usa el “determinado” del indicador, como se muestra en la figura 5, llamando setProgress(max, progress, false) El primer parámetro es lo que se muestra es, como 100. El segundo es cuánto se completó. El último indica que se trata de un progreso determinado .

A medida que la operación avance, llama de forma continua a setProgress(max, progress, false) con un valor actualizado de progress y vuelve a emitir la notificación, como se muestra en el siguiente ejemplo.

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());

Al final de la operación, progress debe ser igual a max. Puedes dejar el la barra de progreso para mostrar que la operación finalizó o quitarla. En cualquier caso, actualizar el texto de la notificación para mostrar que la operación se completó Quitar la barra de progreso, llama a setProgress(0, 0, false).

Para mostrar una barra de progreso indeterminado (una barra que no indica la finalización porcentaje), llama a setProgress(0, 0, true). El resultado es un indicador que tiene el mismo estilo que la barra de progreso anterior, excepto que es una barra animación que no indica la finalización. La animación de progreso se ejecuta hasta llama a setProgress(0, 0, false) y, luego, actualiza la notificación para quitar el indicador de actividad.

Recuerda cambiar el texto de la notificación para indicar que la operación se que se completó.

Cómo establecer una categoría para todo el sistema

Android usa categorías predefinidas para todo el sistema para determinar si debe molestarse. al usuario con una notificación determinada cuando habilita No interrumpir automático.

Si tu notificación pertenece a una de las categorías de notificación definidas en NotificationCompat, como CATEGORY_ALARM, CATEGORY_REMINDER, CATEGORY_EVENT, o CATEGORY_CALL: declarar pasando la categoría adecuada a 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);

El sistema usa esta información sobre la categoría de tu notificación para hacer decisiones sobre mostrar tu notificación cuando el dispositivo está en modo No molestar Interrumpir. Sin embargo, no es necesario que establezcas una categoría para todo el sistema. Solo hazlo si tus notificaciones coinciden con una de las categorías definidas en NotificationCompat

Cómo mostrar un mensaje urgente

Es posible que tu app deba mostrar un mensaje urgente, urgente, como llamada telefónica entrante o una alarma que está sonando. En estas situaciones, puedes asociar un el intent de pantalla completa con la notificación.

Cuando se invoca la notificación, los usuarios ven una de las siguientes opciones, según la el estado de bloqueo del dispositivo:

  • Si el dispositivo del usuario está bloqueado, aparece una actividad en pantalla completa que cubre la pantalla de bloqueo.
  • Si el dispositivo del usuario está desbloqueado, la notificación aparece que incluya opciones para manejar o descartar la notificación.

El siguiente fragmento de código demuestra cómo asociar la notificación con un intent de pantalla completa:

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);

Cómo establecer la visibilidad de la pantalla de bloqueo

Para controlar el nivel de detalle visible en la notificación desde la pantalla de bloqueo, haz lo siguiente: llamar setVisibility() y especifica uno de los siguientes valores:

  • VISIBILITY_PUBLIC: se mostrará todo el contenido de la notificación en la pantalla de bloqueo.

  • VISIBILITY_SECRET: no se muestra ninguna parte de la notificación en la pantalla bloqueada.

  • VISIBILITY_PRIVATE: solo información básica, como el ícono de la notificación y el contenido , se muestra en la pantalla de bloqueo. Todo el contenido de la notificación no un programa de TV.

Cuando configuras VISIBILITY_PRIVATE, también puedes proporcionar una versión alternativa de el contenido de las notificaciones que oculta ciertos detalles. Por ejemplo, una app de SMS podría mostrar una notificación con el mensaje "Tienes 3 mensajes de texto nuevos", pero oculta el contenido del mensaje y los remitentes. Para ofrecer esta alternativa primero, crea la notificación alternativa con NotificationCompat.Builder como de costumbre. Luego, adjunta la notificación alternativa a la notificación normal con setPublicVersion()

Ten en cuenta que el usuario siempre tiene el máximo control sobre si su son visibles en la pantalla de bloqueo y pueden controlarlas según tu canales de notificaciones de la app.

Cómo actualizar una notificación

Para actualizar una notificación después de emitirla, llama a NotificationManagerCompat.notify() y le pasas el mismo ID que usaste. antes. Si se descarta la notificación anterior, se crea una nueva. en su lugar.

De manera opcional, puedes llamar setOnlyAlertOnce() para que la notificación interrumpa al usuario, con sonido, vibración o imagen pistas; solo la primera vez que aparece la notificación, y no en el futuro actualizaciones.

Cómo quitar una notificación

Las notificaciones permanecen visibles hasta que alguna de estas acciones tiene lugar:

  • El usuario descarta la notificación.
  • El usuario presiona la notificación si llamas a setAutoCancel() cuando haces lo siguiente: crea la notificación.
  • Tú llamas cancel() para un ID de notificación específico. Este método también borra las entradas notificaciones.
  • Tú llamas cancelAll(): lo que quita todas las notificaciones que emitiste previamente.
  • Transcurrirá la duración especificada si estableces un tiempo de espera al crear la notificación, con setTimeoutAfter() Si es necesario, puedes cancelar una notificación antes del tiempo de espera especificado transcurra la duración establecida.

Prácticas recomendadas para apps de mensajería

Ten en cuenta las prácticas recomendadas que se enumeran aquí cuando crees notificaciones para tus las apps de mensajería y chat.

Usa MessagingStyle

A partir de Android 7.0 (nivel de API 24), Android proporciona un estilo de notificación específicamente para contenido de mensajería. Con el NotificationCompat.MessagingStyle puedes cambiar varias de las etiquetas que aparecen en la notificación, incluidos el título de la conversación, los mensajes adicionales y la vista de contenido de la notificación.

En el siguiente fragmento de código, se muestra cómo personalizar el estilo de una notificación con la clase 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();

A partir de Android 9.0 (nivel de API 28), también es necesario usar el Person para obtener un y una renderización óptima de la notificación y sus avatares.

Cuando uses NotificationCompat.MessagingStyle, haz lo siguiente:

  • Llamada MessagingStyle.setConversationTitle() para definir un título para chats en grupo de más de dos personas. Un buen título de la conversación puede ser el nombre del chat en grupo o, si no tengan un nombre, una lista de los participantes de la conversación. Sin ella, el mensaje puede confundirse como perteneciente a una conversación uno a uno con el remitente del mensaje más reciente de la conversación.
  • Usa el MessagingStyle.setData() para incluir mensajes multimedia, como imágenes. Tipos de MIME del patrón image/*.

Cómo usar Respuesta directa

Respuesta directa permite al usuario responder en línea a un mensaje.

  • Después de que un usuario responda con la acción de respuesta en línea, usa MessagingStyle.addMessage() para actualizar la notificación MessagingStyle, y no te retractes ni canceles la notificación. Si no cancelas la notificación, el usuario puede enviar varias respuestas desde la notificación.
  • Para que la acción de respuesta en línea sea compatible con Wear OS, llama a Action.WearableExtender.setHintDisplayInlineAction(true)
  • Usa el addHistoricMessage() para proporcionar contexto a una conversación de respuesta directa agregando mensajes a la notificación.

Habilitar Respuesta inteligente

  • Para habilitar Respuesta inteligente, llama setAllowGeneratedResponses(true) en la acción de respuesta. Esto hace que las respuestas de Respuesta inteligente estén disponibles para cuando la notificación se conecta a un dispositivo Wear OS. Respuesta inteligente las respuestas son generadas por un modelo de aprendizaje automático totalmente en el reloj que usa el contexto proporcionado por NotificationCompat.MessagingStyle notificación y no se suben datos a Internet para generar la de respuestas ante incidentes.

Agrega metadatos de notificación