arrow_back Volver
Inicio keyboard_arrow_right Artículos keyboard_arrow_right Artículo

Push Notification usando canales android

Marines Méndez

Software Developer

av_timer 3 Min. de lectura

remove_red_eye 9491 visitas

calendar_today 29 Octubre 2019

Push notifications es una tecnología que permite enviar mensajes a los SmartPhones, incluso cuando el usuario no está utilizando activamente la aplicación, son una excelente herramienta de marketing para cualquier persona con una aplicación móvil, ya que te ayudan a mantenerte en contacto con tus usuarios.

Android 8.0 Oreo trajo consigo algunos cambios en las notificaciones ya que podemos separar las notificaciones de una aplicación en canales de notificación . Todas las notificaciones que se publican en el mismo canal tienen el mismo comportamiento, por ejemplo, podríamos crear un canal para las notificaciones más urgentes de nuestra aplicación, donde cada notificación se anuncia con un sonido de alerta, vibración y una luz de notificación, y luego crear "más silencioso" canales para el resto de las notificaciones de su aplicación. Android Oreo también brinda a los usuarios más control sobre las notificaciones que nunca antes, ya que en Android 8.0 los usuarios pueden modificar la configuración de cualquier canal de notificación que esté presente en su dispositivo.

Primero tenemos que iniciar el servicio para poder usar las notificaciones:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

Ahora vamos a crear nuestro canal, creamos una instancia y agregaremos tres argumentos el id del canal, nombre del canal y por último la importancia.

NotificationChannel notificationChannel = new NotificationChannel("NOTIFICATION_URGENT _ID", "Urgent", NotificationManager.IMPORTANCE_HIGH);

Agregamos una pequeña descripcion de este canal.

notificationChannel.setDescription("Channel description");

Habilitamos la luz en el dispositivo y especificamos el color

notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);

Habilitamos la vibración del dispositivo y especificamos el patron de vibración

notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});

También podemos especificarle un sonido, este debemos de guardarlo en una carpeta raw en nuestro proyecto.

Uri.parse("android.resource://" +
context.getPackageName() + "your_sound_file_name.mp3")
notificationChannel.setSound();

Tambien podemos configurar la notificacion para que forme parte de un grupo de notificaciones. Las notificaciones agrupadas pueden mostrarse en un clúster o pila en dispositivos que admiten dicha representación.

notificationChannel.setGroup("ID_GROUP");

Colocamos true en setShowBadge para que se muestre el icono en la notificacion.

notificationChannel.setShowBadge(true);

Por último creamos el canal

assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);

Vamos a crear un método que se ejecutará cuando el usuario de clic en la notificación esta tiene que retornar un valor tipo PendingIntent también podemos enviar algunos datos a la actividad.

  public PendingIntent onclick(){
       Intent notificationIntent = new Intent(this,
               Main2Activity.class);
       notificationIntent.putExtra("age", "13");
       // set intent so it does not start a new activity
       notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
               | Intent.FLAG_ACTIVITY_SINGLE_TOP);

       return PendingIntent.getActivity(this, 0,
               notificationIntent, 0);
   }

Ya tenemos el canal y el evento clic ahora vamos a crear la notificación usando la clase NotificationCompat.Builder y vamos a especificar el canal al que pertenece la notificación

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

setAutoCancel Establecer esta bandera lo hará para que la notificación se cancele automáticamente cuando el usuario haga clic en el panel.

setWhen Establezca la hora en que ocurrió el evento.

setSmallIcon agregar un icono para la notificacion.

setTicker establece el texto que se muestra en la barra de estado cuando llega la notificación.

setContentIntent Agregaremos nuestro evento clic que creamos anteriormente.

setContentInfo Mostrara un texto del lado derecho de la notificación.

     notificationBuilder.setAutoCancel(true)
               .setDefaults(Notification.DEFAULT_ALL)
               .setWhen(System.currentTimeMillis())
               .setSmallIcon(R.drawable.ic_launcher_background)
               .setTicker("Mensajes")
               .setContentTitle("Titulo")
               .setContentIntent(onclick())
               .setContentText("Esta es una descripción")
               .setContentInfo("New");

Al crear la notificación tenemos que colocarle un id este tiene que ser diferente porque si lanzamos una notificación con el id 3 y queremos mandar otra notificación con el id 3 se reemplaza el anterior y lo que queremos es que el usuario vea todas las notificaciones así que podemos agregarle un id random a las notificaciones con el siguiente código:

       Random random = new Random();
       int m = random.nextInt(9999 - 1000) + 1000;
       assert notificationManager != null;
       notificationManager.notify(/*notification id*/m, notificationBuilder.build());

Crearemos un boton y ejecutaremos el codigo mostrando así la notificación este seria el codigo completo:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

   <Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Enviar"
       android:onClick="message"/><!-- este será el nombre de nuestro método onclick -->

</LinearLayout>

Este sería nuestro MainActivity mucho ojo porque aquí tenemos que crear una segunda actividad Main2Activity ya que esta la usamos en nuestro método onClick.

public class MainActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
   }

   public void message(View view) {
       generateNotification();
   }

   private void generateNotification() {
       NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           NotificationChannel notificationChannel = new NotificationChannel("NOTIFICATION_URGENT _ID", "My Notifications", NotificationManager.IMPORTANCE_HIGH);
           notificationChannel.setDescription("Channel description");
           notificationChannel.enableLights(true);
           notificationChannel.setLightColor(Color.RED);
           notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
           notificationChannel.enableVibration(true);

           notificationChannel.setGroup("id");
           notificationChannel.setShowBadge(true);
           assert notificationManager != null;
           notificationManager.createNotificationChannel(notificationChannel);
       }


       NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "NOTIFICATION_URGENT _ID");

       notificationBuilder.setAutoCancel(true)
               .setDefaults(Notification.DEFAULT_ALL)
               .setWhen(System.currentTimeMillis())
               .setSmallIcon(R.drawable.ic_launcher_background)
               .setTicker("Mensajes")
               .setContentTitle("Titulo")
               .setContentIntent(onClick())
               .setContentText("Esta es una descripción")
               .setContentInfo("New");


       Random random = new Random();
       int m = random.nextInt(9999 - 1000) + 1000;
       assert notificationManager != null;
       notificationManager.notify(/*notification id*/m, notificationBuilder.build());

   }
   public PendingIntent  onClick(){
       Intent notificationIntent = new Intent(this,
               Main2Activity.class);
       notificationIntent.putExtra("age", "13");
       notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
               | Intent.FLAG_ACTIVITY_SINGLE_TOP);
       return PendingIntent.getActivity(this, 0,
               notificationIntent, 0);
   }
}

Resultado:

Texto alternativo

Texto alternativo

Bootcamp Ciencia de Datos

12 semanas de formación intensiva en los conocimientos, fundamentos, y herramientas que necesitas para ser científico de datos

Más información