Code de notification pour Android 12 et plus :
Si votre application cible Android 12, vous devez spécifier la mutabilité de chaque objet PendingIntent créé par votre application. Cette exigence supplémentaire améliore la sécurité de votre application.
Avant Android 12
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Pour Android 12 :
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Créez d'abord un canal :
@RequiresApi(api = Build.VERSION_CODES.O)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "dummy text for channel";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("channel name, name, importance);
mChannel.setShowBadge(false);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "Channel";
}
Exemple de notification :
String channel="";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
RemoteViews mContentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.general_notification_layout_new);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel);
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
builder.setSmallIcon(R.drawable.notification_small_icon_one)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setSound(notificationSound)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setCustomContentView(mContentView)
.setCustomBigContentView(mContentView)
.setContentIntent(contentIntent);
builder.setAutoCancel(true);
Notification notification = builder.build();
mNotificationManager.notify(notificationId, notification);