09.02.2017 Views

creez-des-applications-pour-android

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5 Concepts avancés<br />

Figure 5.7 – La notification contient au moins un titre et un texte<br />

// L'icône sera une petite loupe<br />

int icon = R.drawable.ic_action_search ;<br />

// Le premier titre affiché<br />

CharSequence tickerText = "Titre de la notification" ;<br />

// Daté de maintenant<br />

long when = System.currentTimeMillis();<br />

// La notification est créée<br />

Notification notification = new Notification(icon, tickerText, when);<br />

// Intent qui lancera vers l'activité MainActivity<br />

Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);<br />

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br />

PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, notificat<br />

notification.setLatestEventInfo(MainActivity.this, "Titre", "Texte", contentIntent);<br />

Enfin, il est possible de rajouter <strong>des</strong> flags à une notification afin de modifier son comportement :<br />

— FLAG_AUTO_CANCEL <strong>pour</strong> que la notification disparaisse dès que l’utilisateur appuie <strong>des</strong>sus.<br />

— FLAG_ONGOING_EVENT <strong>pour</strong> que la notification soit rangée sous la catégorie « En cours »<br />

dans l’écran <strong>des</strong> notifications, comme à la figure suivante. Ainsi, l’utilisateur saura que le<br />

composant qui a affiché cette notification est en train de faire une opération.<br />

Les flags s’ajoutent à l’aide de l’attribut flags qu’on trouve dans chaque notification :<br />

notification.flags = FLAG_AUTO_CANCEL | FLAG_ONGOING_EVENT;<br />

5.2.4.2.2 Gérer vos notifications Votre application n’est pas la seule à envoyer <strong>des</strong> notifications,<br />

toutes les <strong>applications</strong> peuvent le faire ! Ainsi, <strong>pour</strong> gérer toutes les notifications de toutes<br />

les <strong>applications</strong>, Android fait appel à un gestionnaire de notifications, représenté par la classe<br />

NotificationManager. Comme il n’y a qu’un NotificationManager <strong>pour</strong> tout le système, on<br />

ne va pas en construire un nouveau, on va plutôt récupérer celui du système avec une méthode qui<br />

appartient à la classe Context : Object getSystemService(Context.NOTIFICATION_SERVICE).<br />

Alors réfléchissons : cette méthode appartient à Context, pouvez-vous en déduire quels sont les<br />

composants qui peuvent invoquer le NotificationManager ? Eh bien, les Broadcast Receiver<br />

358

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!