Notificaciones en Android Oreo (8+)

Android Oreo ha traído un montón de cambios. Esto también incluye la forma en que un usuario emite notificaciones en una aplicación. En este artículo, discutiremos los cambios que deben realizarse en el departamento de notificaciones.

Se deben tener en cuenta las siguientes cosas al emitir notificaciones:

  1. Diseño de un canal de notificación
  2. Importancia de cada canal de notificación
  3. La ID de notificación (diferente de la ID del canal) no debe establecerse en cero.

Antes de continuar, asegúrese de agregar esta línea en las dependencias de build.gradle (Módulo: aplicación):

implementation 'com.android.support:appcompat-v7:26.1.0'

Comencemos con la creación de un canal de notificación. El siguiente método crea un canal de notificación:

@RequiresApi(api = Build.VERSION_CODES.O)
void makeNotificationChannel(String id, String name, int importance)
{
    NotificationChannel channel = new NotificationChannel(id, name, importance);
    channel.setShowBadge(true); // set false to disable badges, Oreo exclusive
  
    NotificationManager notificationManager =
         (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  
    assert notificationManager != null;
    notificationManager.createNotificationChannel(channel);
}

Veamos qué hace este método en detalle.

  1. El método acepta id de string, nombre de string, importancia int. .
    • String id: esta es la identificación con la que emite una notificación en el canal de notificación. Utiliza esta identificación exacta para múltiples notificaciones en el mismo canal.
    • Nombre de string: este es el nombre del canal visible cuando alguien toca y navega a Configuración -> Aplicaciones y notificaciones -> [nombre_de_su_aplicación] -> Notificaciones de aplicaciones.
    • importancia int: Este es el nivel de importancia del canal. Los niveles son los siguientes:
      1. NotificationManager.IMPORTANCE_MIN : se muestra solo en el tono de notificación, sin sonido ni vistazo.
      2. NotificationManager.IMPORTANCE_LOW : se muestra en todas partes, no emite sonido, no se asoma.
      3. NotificationManager.IMPORTANCE_DEFAULT : se muestra en todas partes, emite un sonido pero no se asoma.
      4. NotificationManager.IMPORTANCE_HIGH : se muestra en todas partes, emite un sonido y se asoma (interrupción visual).
      5. NotificationManager.IMPORTANCE_MAX : este nivel de importancia generalmente no se usa. Funciona de forma similar a IMPORTANCE_HIGH.
      6. A menudo, se prefiere el parámetro IMPORTANCE_DEFAULT, pero esto produce un sonido de notificación que puede ser molesto. Para silenciar, agregue la siguiente línea en el método makeNotificationChannel() , justo antes de la última línea.

        channel.setSound(null, null);
        
  2. A continuación, el método crea el canal con los parámetros.
  3. setShowBadge(true) hace que la notificación esté disponible mediante la función de puntos de notificación de Oreo.
  4. Finalmente, el canal de notificación se crea mediante el método createNotificationChannel() de NotificationManager.
  5. Ahora emitamos una notificación. Usaremos NotificationCompat para la compatibilidad con versiones anteriores.

    void issueNotification()
    {
      
        // make the channel. The method has been discussed before.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            makeNotificationChannel("CHANNEL_1", "Example channel", NotificationManager.IMPORTANCE_DEFAULT);
        }
        // the check ensures that the channel will only be made
        // if the device is running Android 8+
      
        NotificationCompat.Builder notification =
                    new NotificationCompat.Builder(this, "CHANNEL_1");
        // the second parameter is the channel id.
        // it should be the same as passed to the makeNotificationChannel() method
      
        notification
            .setSmallIcon(R.mipmap.ic_launcher) // can use any other icon
            .setContentTitle("Notification!")
            .setContentText("This is an Oreo notification!")
            .setNumber(3); // this shows a number in the notification dots
      
        NotificationManager notificationManager =
                    (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
      
        assert notificationManager != null;
        notificationManager.notify(1, notification.build());
        // it is better to not use 0 as notification id, so used 1.
    }

    La ejecución procede de esta manera:

  • Primero, el método anterior crea inicialmente un canal de notificación con id = «CHANNEL_1» y el nombre «Canal de ejemplo». La identificación no está visible en ninguna parte, pero el nombre se puede ver abriendo la opción «Notificaciones de la aplicación» de la página de información de la aplicación.

  • Luego se crea un objeto NotificationCompat.Builder especificando el contexto y la identificación como «CHANNEL_1». Se puede mencionar una identificación de canal diferente siempre que se haga con el método makeNotificationChannel() .
    El resto se explica por sí mismo. El método setNumber() muestra un número en el punto de notificación de la aplicación.


  • Finalmente, es mejor que la identificación de la notificación (aquí 1) no se establezca en 0, ya que en los casos en que la notificación se usa para un servicio en primer plano , no se mostrará si la identificación es 0. Al ejecutar el método issueNotification() , obtenemos el siguiente notificación:

Publicación traducida automáticamente

Artículo escrito por SayantanRoychowdhury y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *