NotificationCompat.Builder est obsolète dans Android O

Après la mise à niveau de mon projet vers Android O

buildToolsVersion "26.0.1" 

Lint dans Android Studio affiche un avertissement obsolète pour la méthode de création de notification suivante:

 new NotificationCompat.Builder(context) 

Le problème est le suivant: les développeurs Android mettent à jour leur documentation décrivant NotificationChannel pour prendre en charge les notifications dans Android O, et nous fournissent un extrait de code, mais avec le même avertissement obsolète:

 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(); 

Aperçu des notifications

Ma question: existe-t-il une autre solution pour la notification de la construction, tout en supportant Android O?

Une solution que j’ai trouvée consiste à transmettre l’ID de canal en tant que paramètre dans le constructeur Notification.Builder. Mais cette solution n’est pas exactement réutilisable.

 new Notification.Builder(MainActivity.this, "channel_id") 

Il est mentionné dans la documentation que la méthode de générateur NotificationCompat.Builder(Context context) est obsolète. Et nous devons utiliser le constructeur qui a le paramètre channelId :

 NotificationCompat.Builder(Context context, Ssortingng channelId) 

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

Ce constructeur est devenu obsolète au niveau de l’API 26.0.0-beta1. utilisez plutôt NotificationCompat.Builder (Context, Ssortingng). Toutes les notifications postées doivent spécifier un identifiant NotificationChannel.

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

Ce constructeur est déconseillé au niveau 26 de l’API. Utilisez plutôt Notification.Builder (Context, Ssortingng). Toutes les notifications postées doivent spécifier un identifiant NotificationChannel.

Si vous souhaitez réutiliser les parameters de générateur, vous pouvez créer le générateur avec channelId, puis transmettre ce générateur à une méthode d’assistance et définir vos parameters préférés dans cette méthode.

entrer la description de l'image ici

Voici le code de travail pour toutes les versions Android à partir de API LEVEL 26+ avec rétrocompatibilité.

  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()); 

UPDATE pour l’API 26 pour définir la priorité maximale

  NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Ssortingng 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()); 

Appelez le constructeur 2-arg: Pour la compatibilité avec Android O, appelez support-v4 NotificationCompat.Builder(Context context, Ssortingng channelId) . Lors de l’exécution sous Android N ou antérieur, le channelId sera ignoré. Lors de l’exécution sur Android O, créez également un NotificationChannel avec le même channelId .

Exemple de code obsolète: l’exemple de code sur plusieurs pages JavaDoc telles que Notification.Builder appelant new Notification.Builder(mContext) est obsolète.

Les constructeurs obsolètes : Notification.Builder(Context context) et v4 NotificationCompat.Builder(Context context) sont déconseillés au profit de Notification[Compat].Builder(Context context, Ssortingng channelId) . (Voir Notification.Builder (android.content.Context) et v4 NotificationCompat.Builder (contexte contextuel) .)

Classe obsolète : L’intégralité de la classe v7 NotificationCompat.Builder est obsolète. (Voir NotificationCompat.Builder pour la v7 .) Auparavant, la NotificationCompat.Builder v7 NotificationCompat.Builder était nécessaire pour prendre en charge NotificationCompat.MediaStyle . Dans Android O, il existe un NotificationCompat.MediaStyle v4 dans le package android.support.v4.media bibliothèque media-compat . Utilisez celui-ci si vous avez besoin de MediaStyle .

API 14+: dans Support Library à partir de la version 26.0.0, les packages support-v4 et support-v7 prennent tous deux en charge un niveau minimum d’API de 14. Les noms v # sont historiques.

Voir les révisions récentes de la bibliothèque de support .

Au lieu de rechercher Build.VERSION.SDK_INT >= Build.VERSION_CODES.O comme le Build.VERSION.SDK_INT >= Build.VERSION_CODES.O de nombreuses réponses, il existe un moyen légèrement plus simple –

Ajoutez la ligne suivante à la section d’ application du fichier AndroidManifest.xml , comme indiqué dans la section Configurer une application client de messagerie Firebase Cloud sur Android doc:

   

Ajoutez ensuite une ligne avec un nom de canal dans le fichier values ​​/ ssortingngs.xml :

 default 

Après cela, vous pourrez utiliser la nouvelle version du constructeur NotificationCompat.Builder avec 2 parameters (l’ancien constructeur avec 1 paramètre étant obsolète dans Android Oreo):

 private void sendNotification(Ssortingng title, Ssortingng 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, getSsortingng(R.ssortingng.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()); } 

Voici l’exemple de code qui fonctionne dans Android Oreo et moins 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.getSsortingng(R.ssortingng.getTitel)) .setTicker(context.getSsortingng(R.ssortingng.text)) .setContentText(message) .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true); notificationManager.notify(requestCode, builder.build()); 

Échantillon simple

  public void showNotification (Ssortingng from, Ssortingng notification, Intent intent) { PendingIntent pendingIntent = PendingIntent.getActivity( context, Notification_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT ); Ssortingng 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); } 
 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(); 

Le code correct sera:

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

avec la dépendance 26.0.1 et les nouvelles dépendances mises à jour telles que 28.0.0.

Certains utilisateurs utilisent ce code sous la forme de ceci:

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

Donc, Logic est la méthode que vous déclarerez ou initierez alors la même méthode sur le côté droit sera utilisée pour l’allocation. si dans Leftside de = vous utiliserez une méthode, la même méthode sera utilisée à droite de = pour Allocation avec new.

Essayez ce code … Cela fonctionnera sûrement

Ce constructeur est obsolète au niveau de l’API 26.1.0. utilisez plutôt NotificationCompat.Builder (Context, Ssortingng). Toutes les notifications postées doivent spécifier un identifiant NotificationChannel.

J’ai essayé toutes les solutions ici, mais aucune ne fonctionne pour moi. C’est l’erreur que j’ai:

 Application binary: C:/Moje/QtProjects/build-MuzikaPlayer-Android_for_armeabi_v7a_GCC_4_9_Qt_5_11_2_for_Android_ARMv7-Vydu00e1nu00ed/libMuzika.so Android build platform: android-28 . . C:\Moje\QtProjects\build-MuzikaPlayer-Android_for_armeabi_v7a_GCC_4_9_Qt_5_11_2_for_Android_ARMv7-Vydu00e1nu00ed\android-build\src\cz\jech\muzika\MuzikaService.java:106: error: constructor Builder in class Builder cannot be applied to given types; NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) ^ required: Context found: MuzikaService,Ssortingng reason: actual and formal argument lists differ in length Note: Some input files use or override a deprecated API. Note: Recomstack with -Xlint:deprecation for details. 1 error 

Quel est le problème ici? Sans le deuxième argument (CHANNEL_ID), cela fonctionne, mais j’obtiens l’avertissement de dépréciation.