NotificationCompat.Constructor obsoleto en Android O


Después de actualizar mi proyecto a Android O

buildToolsVersion "26.0.1"

Lint en Android Studio muestra una advertencia obsoleta para el método follow notification builder:

new NotificationCompat.Builder(context)

El problema es: Los desarrolladores de Android actualizan su documentación describiendo NotificationChannel para admitir notificaciones en Android O, y nos proporcionan un fragmento, pero con la misma advertencia obsoleta:

Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();  

Descripción general de las notificaciones

Mi pregunta: ¿Hay alguna otra solución para la creación de notificaciones, y todavía es compatible con Android O?

Una solución que encontré es pasar el ID del canal como parámetro en la Notificación.Constructor constructor. Pero esta solución no es exactamente reutilizable.

new Notification.Builder(MainActivity.this, "channel_id")
Author: Shree, 2017-08-02

8 answers

Se menciona en la documentación que el método builder NotificationCompat.Builder(Context context) ha sido obsoleto. Y tenemos que usar el constructor que tiene el parámetro channelId:

NotificationCompat.Builder(Context context, String channelId)

Https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

Este constructor fue obsoleto en el nivel de API 26.0.0-beta1. utilizar NotificationCompat.Constructor (Contexto, Cadena) en su lugar. Todo publicado Las notificaciones deben especificar un NotificationChannel Id.

Https://developer.android.com/reference/android/app/Notification.Builder.html

Este constructor fue obsoleto en el nivel de API 26. utilizar Notificación.Constructor (Contexto, Cadena) en su lugar. Todo publicado Las notificaciones deben especificar un ID de NotificationChannel.

Si desea reutilizar los configuradores del constructor, puede crear el constructor con el channelId, y pasar ese constructor a un método helper y establecer su configuración preferida en ese método.

 77
Author: Bob,
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-08-02 15:52:25

introduzca la descripción de la imagen aquí

Aquí está el código de trabajo para todas las versiones de Android a partir de NIVEL de API 26+ con compatibilidad con versiones anteriores.

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker("Hearty365")
                .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                .setContentTitle("Default notification")
                .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                .setContentInfo("Info");

NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());

ACTUALIZACIÓN para API 26 para establecer prioridad máxima

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }


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

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("Hearty365")
       //     .setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("Default notification")
            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .setContentInfo("Info");

    notificationManager.notify(/*notification id*/1, notificationBuilder.build());
 68
Author: Aks4125,
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-08-07 04:10:07

Llama al constructor 2-arg: Para compatibilidad con Android O, llama a support-v4 NotificationCompat.Builder(Context context, String channelId). Cuando se ejecuta en Android N o anterior, se ignorará channelId. Cuando se ejecuta en Android O, también crea un NotificationChannel con el mismo channelId.

Código de muestra desactualizado: El código de muestra en varias páginas de JavaDoc, como Notificación.Builder llamar a new Notification.Builder(mContext) está desactualizado.

Obsoleto constructores: Notification.Builder(Context context) y v4 NotificationCompat.Builder(Context context) están en desuso en favor de Notification[Compat].Builder(Context context, String channelId). [Véase Notificación.Constructor (android.contenido.Context) y v4 NotificationCompat.Builder (Context context) .)

Clase obsoleta: Toda la clase v7 NotificationCompat.Builder está en desuso. (Véase v7 NotificationCompat.Constructor .) Anteriormente, v7 NotificationCompat.Builder era necesario para soportar NotificationCompat.MediaStyle. En Android O, hay un v4 NotificationCompat.MediaStyle en el paquete media-compat library 's android.support.v4.media. Use ese si necesita MediaStyle.

API 14+: En la biblioteca de soporte de 26.0.0 y versiones posteriores, los paquetes support-v4 y support-v7 admiten un nivel de API mínimo de 14. Los nombres de v # son históricos.

Ver Revisiones Recientes de la Biblioteca de Soporte.

 20
Author: Jerry101,
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-08-09 01:15:10

En lugar de buscar Build.VERSION.SDK_INT >= Build.VERSION_CODES.O como sugieren muchas respuestas, hay una forma un poco más simple:

Agregue la siguiente línea a la sección applicationde AndroidManifest.archivo xml como se explica en el Configurar una aplicación Cliente de Mensajería en la nube Firebase en Android doc:

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id" 
        android:value="@string/default_notification_channel_id" />

Luego agregue una línea con un nombre de canal a los valores/cadenas .archivo xml:

<string name="default_notification_channel_id">default</string>

Después de que usted será capaz de utilizar la nueva versión de NotificationCompat.Constructor constructor con 2 parámetros (ya que el antiguo constructor con 1 parámetro ha sido obsoleto en Android Oreo):

private void sendNotification(String title, String body) {
    Intent i = new Intent(this, MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pi = PendingIntent.getActivity(this,
            0 /* Request code */,
            i,
            PendingIntent.FLAG_ONE_SHOT);

    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, 
        getString(R.string.default_notification_channel_id))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pi);

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

    manager.notify(0, builder.build());
}
 14
Author: Alexander Farber,
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-03-30 15:29:39

Aquí está el código de ejemplo, que funciona en Android Oreo y menos que Oreo.

  NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                int importance = NotificationManager.IMPORTANCE_DEFAULT;
                NotificationChannel notificationChannel = new NotificationChannel("ID", "Name", importance);
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new NotificationCompat.Builder(getApplicationContext(), notificationChannel.getId());
            } else {
                builder = new NotificationCompat.Builder(getApplicationContext());
            }

            builder = builder
                    .setSmallIcon(R.drawable.ic_notification_icon)
                    .setColor(ContextCompat.getColor(context, R.color.color))
                    .setContentTitle(context.getString(R.string.getTitel))
                    .setTicker(context.getString(R.string.text))
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true);
            notificationManager.notify(requestCode, builder.build());
 9
Author: Arpit,
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-16 10:13:08

Muestra simple

    public void showNotification (String from, String notification, Intent intent) {
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context,
                Notification_ID,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );


        String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }


        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
        Notification mNotification = builder
                .setContentTitle(from)
                .setContentText(notification)

//                .setTicker("Hearty365")
//                .setContentInfo("Info")
                //     .setPriority(Notification.PRIORITY_MAX)

                .setContentIntent(pendingIntent)

                .setAutoCancel(true)
//                .setDefaults(Notification.DEFAULT_ALL)
//                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                .build();

        notificationManager.notify(/*notification id*/Notification_ID, mNotification);

    }
 5
Author: Mehul,
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-01-30 12:32:42
Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();  

El código correcto será:

Notification.Builder notification=new Notification.Builder(this)

Con dependencia 26.0.1 y nuevas dependencias actualizadas como 28.0.0.

Algunos usuarios usan este código en la forma de esto :

Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.

Entonces, la lógica es el Método que declarará o inicializará, luego el mismo método en el lado derecho se usará para la Asignación. si en el lado izquierdo de = se utilizará algún método, entonces el mismo método se utilizará en el lado derecho de = para la asignación con nuevo.

Prueba esto code...It seguro que funcionará

 2
Author: Pradeep Sheoran,
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-26 14:19:33

Este constructor fue obsoleto en el nivel de API 26.1.0. utilice NotificationCompat.Constructor (Contexto, Cadena) en su lugar. Todas las notificaciones publicadas deben especificar un Id de NotificationChannel.

 1
Author: Sandeep 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-05-04 06:38:26