Cómo crear una notificación con NotificationCompat.¿Constructor?


Necesito crear una notificación simple que se mostrará en la barra de notificaciones junto con el sonido y el icono si es posible? También necesito que sea compatible con Android 2.2, así que encontré que NotificationCompat.Builder funciona con todas las API anteriores a 4. Si hay una solución mejor, no dude en mencionarla.

Author: Vladimir, 2012-12-16

7 answers

El NotificationCompat.Builder es la forma más fácil de crear Notifications en todas las versiones de Android. Incluso puedes usar funciones que están disponibles con Android 4.1. Si su aplicación se ejecuta en dispositivos con Android >=4.1, se usarán las nuevas características, si se ejecuta en Android

Para crear una notificación simple, simplemente haga (consulte Guía de la API de Android sobre Notificaciones):

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setContentIntent(pendingIntent); //Required on Gingerbread and below

Tienes que establecer al menos smallIcon, contentTitle y contentText. Si se le olvida uno, la notificación no se mostrará.

Cuidado: En Gingerbread y debajo tienes que establecer la intención de contenido, de lo contrario se lanzará un IllegalArgumentException.

Para crear una intención que no hace nada, use:

final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Puedes añadir sonido a través del builder, es decir, un sonido desde el RingtoneManager:

mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

La Notificación se añade a la barra a través del NotificationManager:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());
 114
Author: thaussma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-24 20:29:35

Ejemplo de trabajo:

    Intent intent = new Intent(ctx, HomeActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder b = new NotificationCompat.Builder(ctx);

    b.setAutoCancel(true)
     .setDefaults(Notification.DEFAULT_ALL)
     .setWhen(System.currentTimeMillis())         
     .setSmallIcon(R.drawable.ic_launcher)
     .setTicker("Hearty365")            
     .setContentTitle("Default notification")
     .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
     .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
     .setContentIntent(contentIntent)
     .setContentInfo("Info");


    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, b.build());
 21
Author: Sumoanand,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-31 13:30:04

Hago este método y trabajo bien. (probado en android 6.0.1)

public void notifyThis(String title, String message) {
    NotificationCompat.Builder b = new NotificationCompat.Builder(this.context);
    b.setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.favicon32)
            .setTicker("{your tiny message}")
            .setContentTitle(title)
            .setContentText(message)
            .setContentInfo("INFO");

    NotificationManager nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(1, b.build());
}
 8
Author: Dario Roman Garcia Gonzalez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-10 17:59:36

Puedes probar este código esto funciona bien para mí:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);

    Intent i = new Intent(noti.this, Xyz_activtiy.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0);

    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
    mBuilder.setWhen(20000);
    mBuilder.setTicker("Ticker");
    mBuilder.setContentInfo("Info");
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.home);
    mBuilder.setContentTitle("New notification title");
    mBuilder.setContentText("Notification text");
    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(2,mBuilder.build());
 1
Author: Rohit Lalwani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-22 18:59:59

Forma sencilla de realizar notificaciones

 NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher) //icon
            .setContentTitle("Test") //tittle
            .setAutoCancel(true)//swipe for delete
            .setContentText("Hello Hello"); //content
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, builder.build()
    );
 1
Author: robby dwi hartanto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-31 23:06:28

Notificación en profundidad

CÓDIGO

Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.your_notification_icon)
                        .setContentTitle("Notification Title")
                        .setContentText("Notification ")
                        .setContentIntent(pendingIntent );

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

Conocimiento profundo

La notificación se puede compilar usando Notificación. Constructor o NotificationCompat.Clases de constructor.
Pero si desea compatibilidad con versiones anteriores debe utilizar NotificationCompat.Builder class ya que forma parte de v4 Support library ya que se encarga del trabajo pesado para proporcionar un aspecto consistente y funcionalidades de Notificación para API 4 y superiores.

Notificación básica Propiedades

Una notificación tiene 4 propiedades principales (3 Propiedades de visualización básicas + 1 propiedad de acción de clic)

  • Icono pequeño
  • Título
  • Texto
  • Evento de clic en el botón (Haga clic en evento cuando toque la notificación )

El evento de clic en el botón se hace opcional en Android 3.0 y superior. Esto significa que puedes crear tu notificación usando solo las propiedades de visualización si tu minSdk se dirige a Android 3.0 o superior. Pero si quieres tu notificación para ejecutarse en dispositivos más antiguos que Android 3.0, debe proporcionar Click event de lo contrario verá IllegalArgumentException.

Visualización de la notificación

Las notificaciones se muestran llamando al método notify () de la clase NotificationManger

Notify() parámetros

Hay dos variantes disponibles para el método de notificación

notify(String tag, int id, Notification notification)

O

notify(int id, Notification notification)

El método Notify toma un id entero para identificar de forma única su notificación. Sin embargo, también puede proporcionar una etiqueta de cadena opcional para una mayor identificación de su notificación en caso de conflicto.

Este tipo de conflicto es raro, pero digamos que ha creado alguna biblioteca y otros desarrolladores están usando su biblioteca. Ahora crean su propio notificación y de alguna manera su notificación y otros desarrolladores id de notificación es el mismo entonces se enfrentará a un conflicto.

Notificación después de API 11 (Más control)

API 11 proporciona control adicional sobre el comportamiento de notificación

  • Notificación Desestimación
    De forma predeterminada, si un usuario toca la notificación, realiza el evento de clic asignado, pero no borra la notificación. Si desea que su notificación se borre cuando entonces debe agregar esto

    MBuilder.setAutoClear (true);

  • Evitar que el usuario desestime la notificación
    Un usuario también puede rechazar la notificación por deslizando. Puede desactivar este comportamiento predeterminado agregando esto mientras crea su notificación

    MBuilder.setOngoing (true);

  • Posicionamiento de la notificación
    Puede establecer la prioridad relativa a su notificación mediante

    MBuilder.setOngoing(int pri);

Si su aplicación se ejecuta en una API inferior a 11, su notificación funcionará sin las características adicionales mencionadas anteriormente. Esta es la ventaja de elegir NotificationCompat.Constructor sobre Notificación.Constructor

Notificación después de API 16 (Más informativo)

Con la introducción de API 16, las notificaciones recibieron muchas características nuevas
La notificación puede ser mucho más informativa.
Puede agregar una imagen grande a su logotipo. Digamos que recibes un mensaje de una persona ahora con el mBuilder.setLargeIcon (Mapa de bits mapa de bits) puede mostrar la foto de esa persona. Así que en la barra de estado aparecerá el icono cuando se desplaza verá la foto de la persona en lugar del icono. Hay otras características también

  • Añadir un contador en la notificación
  • Mensaje de Ticker cuando vea la notificación por primera vez
  • Notificación ampliable
  • Notificación multilínea y así sucesivamente
 1
Author: Rohit Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 17:23:58

Utilice este código

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());
 0
Author: Faxriddin Abdullayev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-17 12:00:23