Junior
Comment créer une notification sur Android?
sobes.tech IA
Réponse de l'IA
Pour créer une notification sur Android, vous devez suivre les étapes suivantes:
- Créer un canal de notification (pour API niveau 26 et supérieur).
- Construire la notification à l'aide de
NotificationCompat.Builder. - Afficher la notification via le gestionnaire de notifications.
// Création du canal de notification (API 26+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "my_channel_id";
CharSequence channelName = "Mon Canal";
String channelDescription = "Description de Mon Canal";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
channel.setDescription(channelDescription);
// Enregistrement du canal dans le système
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
// Création du constructeur de notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "my_channel_id") // Spécifier l'ID du canal
.setSmallIcon(R.drawable.ic_notification) // Icône de la notification
.setContentTitle("Titre de la notification") // Titre
.setContentText("Texte de la notification") // Texte
.setPriority(NotificationCompat.PRIORITY_DEFAULT); // Priorité
// Créer un PendingIntent pour l'action lors du clic sur la notification
// Par exemple, ouvrir une activité
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); // Drapeau pour API S+
builder.setContentIntent(pendingIntent);
// Afficher la notification
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
int notificationId = 1; // ID unique pour la notification
notificationManagerCompat.notify(notificationId, builder.build());
Composants principaux de la notification:
- Icône petite:
setSmallIcon(), affichée dans la barre d'état. - Titre:
setContentTitle(), texte principal de la notification. - Texte:
setContentText(), texte supplémentaire. - Canal de notification (API 26+): Groupe de notifications avec paramètres communs.
- PendingIntent: Action effectuée lors du clic sur la notification.
Vous pouvez également ajouter une grande image (setStyle(new NotificationCompat.BigPictureStyle())), des boutons d'action (addAction()), configurer le son, la vibration et d'autres paramètres.