Android – Cours 5 – Notifications
Ce jour
- Qu’est-ce qu’une notification
- Principe
- Exemple
- Modifier une notification
- Supprimer une notification
Qu’est-ce qu’une notification
- Notifier l’utilisateur
- une tâche est terminée
- un message est arrivé
- …
- Donner à l’utilisateur des outils utilisables hors de l’activité
- Contrôle de player musical
- Barre de progression
- …
- Vos propres usages (à inventer)
Principe
- On crée une notification avec un objet de type
NotificationCompat.Builder - On utilise un objet
NotificationManager, fourni par le système pour gérer les notifications (les afficher, etc.)
Exemple
Construire la notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Mes notifications de test")
.setContentText("Ma première notif!");
Exemple (suite)
Envoyer la notification avec le notification manager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(mNotificationId, mBuilder.build());
NB: attention à l’ID
Ajouter une action
- Créer ou récupérer un Intent
- L’inclure dans un PendingIntent
Intent rIntent=this.getIntent();
ou
Intent rIntent = new Intent(this, ResultActivity.class);
PendingIntent rPendingIntent = PendingIntent.getActivity( this, 0, rIntent, PendingIntent.FLAG_UPDATE_CURRENT ); mBuilder.setContentIntent(rPendingIntent);
Modifier une notification
- Récupérer le
NotificationCompat.Builder - Lui appliquer les modifications
- Ré-envoyer la notification avec le même ID
mBuilder
.setContentText("My new notification test")
.setNumber(++ccMsg);
mNotificationManager.notify(mNotificationId, mBuilder.build());
Supprimer une notification
- Suppression manuelle par l’utilisateur (glisser)
- Suppression de ttes les notifs par l’utilisateur (Effacer tout)
- Si
setAutoCancel()a été appelé : l’utilisateur touche la notif - Appel de la fonction
cancel()avec l’ID de la notif - Appel de la fonction
cancelAll()
More
- On peut insérer des contrôles dans une notification
- Style Big View
- Android 8 introduit des canaux de notification (notification channels)
- Notifications quand l’appli est en arrière plan
- Notifications push (Google Cloud Messaging for Android)