NotificationCompat con API 26


No veo ninguna información sobre cómo usar NotificationCompat con Android O's Notification Channels

Veo un nuevo Constructor que toma un channelId pero cómo tomar una notificación Compat y usarla en un NotificationChannel ya que createNotificationChannel toma un objeto NotificationChannel

Author: tyczj, 2017-06-08

4 answers

Crear el NotificationChannel solo si API >= 26

public void initChannels(Context context) {
    if (Build.VERSION.SDK_INT < 26) {
        return;
    }
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel channel = new NotificationChannel("default",
                                                          "Channel name",
                                                          NotificationManager.IMPORTANCE_DEFAULT);
    channel.setDescription("Channel description");
    notificationManager.createNotificationChannel(channel);
}

Y luego simplemente use:

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "default");

Por lo tanto, sus notificaciones funcionan con API 26 (con canal) y por debajo (sin).

 95
Author: stankocken,
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-06-13 14:54:16

Declare Notification Manager:

   final NotificationManager mNotific=            
   (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    CharSequence name="Ragav";
    String desc="this is notific";
    int imp=NotificationManager.IMPORTANCE_HIGH;
    final String ChannelID="my_channel_01";

Canal de Notificación

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
    {
      NotificationChannel mChannel = new NotificationChannel(ChannelID, name, 
     imp);
            mChannel.setDescription(desc);
            mChannel.setLightColor(Color.CYAN);
            mChannel.canShowBadge();
            mChannel.setShowBadge(true);
            mNotific.createNotificationChannel(mChannel);
        }

    final int ncode=101;

    String Body="This is testing notific";

Creador de notificaciones

        Notification n= new Notification.Builder(this,ChannelID)
                .setContentTitle(getPackageName())
                .setContentText(Body)
                .setBadgeIconType(R.mipmap.ic_launcher)
                .setNumber(5)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setAutoCancel(true)
                .build();

NotificationManager notificar al usuario:

            mNotific.notify(ncode, n);
 8
Author: Ragavendra M,
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-09-04 07:03:10

NotificationChannel agrupa varias notificaciones en canales. Básicamente da más control del comportamiento de notificación al usuario. Puede leer más sobre el Canal de Notificaciones y su implementación en Trabajando con el Canal de Notificaciones / Con el Ejemplo

El canal de notificación solo es aplicable para Android Oreo.

 //Notification channel should only be created for devices running Android 26
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  NotificationChannel notificationChannel = new NotificationChannel("unique_channel_id","channel_name",NotificationManager.IMPORTANCE_DEFAULT);

  //Boolean value to set if lights are enabled for Notifications from this Channel
  notificationChannel.enableLights(true);

  //Boolean value to set if vibration is enabled for Notifications from this Channel
  notificationChannel.enableVibration(true);

  //Sets the color of Notification Light
  notificationChannel.setLightColor(Color.GREEN);

  //Set the vibration pattern for notifications. Pattern is in milliseconds with the format {delay,play,sleep,play,sleep...}
  notificationChannel.setVibrationPattern(new long[]{500,500,500,500,500});

  //Sets whether notifications from these Channel should be visible on Lockscreen or not
  notificationChannel.setLockscreenVisibility( Notification.VISIBILITY_PUBLIC);
}  

Tenga en cuenta que el ID de canal pasado al constructor actúa como el identificador único para ese Canal de notificación. Ahora crea el Notificación como se muestra a continuación

// Creating the Channel
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);

Para agregar cualquier Notificación a este Canal, simplemente pase el ID del canal como se muestra a continuación

//We pass the unique channel id as the second parameter in the constructor
NotificationCompat.Builder notificationCompatBuilder=new NotificationCompat.Builder(this,NOTIFICATION_CHANNEL_ID);

//Title for your notification
notificationCompatBuilder.setContentTitle("This is title");

//Subtext for your notification
notificationCompatBuilder.setContentText("This is subtext");

//Small Icon for your notificatiom
notificationCompatBuilder.setSmallIcon(R.id.icon);

//Large Icon for your notification 
notificationCompatBuilder.setLargeIcon(  BitmapFactory.decodeResource(getResources(),R.id.icon));

notificationManager.notify( NOTIFICATION_ID,notificationCompatBuilder.build());
 0
Author: IrshadKumail,
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-04-30 19:40:51

Tenga cuidado si hizo todo el trabajo y no obtuvo ningún resultado. En algunos dispositivos, debe establecer la prioridad de notificación .

   final NotificationCompat.Builder mBuilder = new 
    NotificationCompat.Builder(mContext, "default")
    .setPriority(Notification.PRIORITY_MAX);
 0
Author: Iman Marashi,
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-06-01 09:16:52