Le but de ce tutoriel est d’apprendre à utiliser les notifications sous Android, ce système facilite les interactions entre votre application et l’utilisateur lors de la survenue d’évènements particuliers.
Le système de notifications fourni une indication permettant de prévenir l’utilisateur de certains évènements (arriver d’un SMS, mail, appel en absence …).
Mise en place
Nous allons créer un projet qui comprendra deux boutons :
- Un pour créer une notification
- Un autre pour en supprimer
Commençons par créer un projet avec les données suivantes :
- Nom du projet : tuto_notification
- SDK : 4.1
- Nom de l’application : Tuto Notification
- Nom du package : com.tutos.android.notification
- Activité : TutoNotificationHomeActivity
Création de la vue principale
Nous allons modifier le fichier “main.xml” afin d’avoir deux boutons.
?xml version="1.0" encoding="utf-8"?
LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/add_notification"
android:id="@+id/add_notification"
/
Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/delete_notification"
android:id="@+id/delete_notification"
/
/LinearLayout
Le fichier “strings.xml” pour rajouter les différentes strings pour le texte des boutons
?xml version="1.0" encoding="utf-8"?
resources
string name="add_notification"Ajouter une notification/string
string name="delete_notification"Supprimer une notification/string
string name="app_name"Tuto Notification/string
/resources
Voici le résultat que vous allez obtenir.
Rajouter le Listener sur les boutons
Nous allons rajouter des “Listener” sur les boutons pour gérer le clic. Ce qui donnera sur la classe “TutoNotificationHomeActivity”
package com.tutos.android.notification;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TutoNotificationHomeActivity extends Activity {
private Button addNotificationBtn;
private Button deleteNotificationBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addNotificationBtn = (Button) findViewById(R.id.add_notification);
addNotificationBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), "Ajout d'une notification", Toast.LENGTH_SHORT).show();
}
});
deleteNotificationBtn = (Button) findViewById(R.id.delete_notification);
deleteNotificationBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Toast.makeText(getBaseContext(), "Suppression d'une notification", Toast.LENGTH_SHORT).show();
}
});
}
}
Création d’une notification.
Nous allons créer une méthode “createNotification” qu’on appelera au clic sur le bouton “Ajouter une notification”. Voici a quoi ressemble cette méthode :
private final void createNotification(){
final NotificationManager mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Intent launchNotifiactionIntent = new Intent(this, TutoNotificationHomeActivity.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
REQUEST_CODE, launchNotifiactionIntent,
PendingIntent.FLAG_ONE_SHOT);
Notification.Builder builder = new Notification.Builder(this)
.setWhen(System.currentTimeMillis())
.setTicker(notificationTitle)
.setSmallIcon(R.drawable.notification)
.setContentTitle(getResources().getString(R.string.notification_title))
.setContentText(getResources().getString(R.string.notification_desc))
.setContentIntent(pendingIntent);
mNotification.notify(NOTIFICATION_ID, builder.build());
}
La création d’une notification est trés simple et s’effectue en suivant les étapes décritent ci-dessous :
- Récupération d’une instance de la classe NotificationManager
- Créer l’intent correspondant à la vue lancée lors du clic sur la notification
- Créer un pending intent décrivant l’intent précédant
- Créer une notification à l’aide d’un Builder, en spécifiant le contexte, le délais de déclenchement de la notification, le titre de la notification, l’icone, le titre et la description du contenu de la notification, l’intent à lier à la notification.
- Le déclenchement de la notification s’effectue à l’aide de la méthode notify
Je vous met l’icone que j’ai utilisé pour la notification ici.
Il suffit maintenant d’appeler la méthode dans votre code, ce qui donnera :
addNotificationBtn = (Button) findViewById(R.id.add_notification);
addNotificationBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
createNotification();
}
});
Il faut rajouter la permission “Vibration” dans l’AndroidManifest.xml
uses-permission android:name="android.permission.VIBRATE" /
et les nouveaux textes dans le fichier “Strings.xml”
string name="notification"Notification www.tutos-android.com/string
string name="notification_title"Ma premiere notification www.tutos-android.com/string
string name="notification_desc"Cliquez sur moi je suis une notification/string
Jelly Bean
La version JellyBean d’Android apporte quelques nouveautés aux notifications :
- Priorité : Ce système permet d’indiquer la priorité d’une notification, plus la notification est prioritaire plus elle sera mise en avant dans la barre de notification. Elle peut posséder l’une des valeurs suivantes (PRIORITY_MAX, PRIORITY_HIGH, PRIORITY_DEFAULT, PRIORITY_LOW, PRIORITY_MIN)
- Nouvelles zones de contenues : Des nouvelles zones de contenus sont disponibles (bigPicture, bigText…) permettant d’enrichir vos notifications
- Actions : Vous pouvez rajouter des actions aux notification à l’aide de la méthode addAction. Ces actions permettent d’offrir à l’utilisateur un autre moyen d’interagir avec les notifications. Ce qui permet par exemple, lors de la réception d’un appel en absence, de rappeler directement la personne ou lui envoyer un sms.
Notification.Builder builder = new Notification.Builder(this)
.setWhen(System.currentTimeMillis())
.setTicker(notificationTitle)
.setSmallIcon(R.drawable.notification)
.setContentTitle(getResources().getString(R.string.notification_title))
.setContentText(getResources().getString(R.string.notification_desc))
.setContentIntent(pendingIntent)
.addAction(R.drawable.play,"Play", PendingIntent.getActivity(getApplicationContext(), 0,
getIntent(), 0, null))
.addAction(R.drawable.pause, "Pause",
PendingIntent.getActivity(getApplicationContext(), 0,
getIntent(), 0, null));
Notification notification = new Notification.BigPictureStyle(builder)
.bigPicture(BitmapFactory.decodeResource(getResources(),
R.drawable.zoidberg_android)).build();
mNotification.notify(NOTIFICATION_ID, notification);
Suppression d’une notification
Nous allons créer une méthode “deleteNotification”, pour supprimer notre notification depuis l’application.
private void deleteNotification(){
final NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
//la suppression de la notification se fait grâce a son ID
notificationManager.cancel(NOTIFICATION_ID);
}
Puis l’appeler dans le code Java au moment du clic
deleteNotificationBtn = (Button) findViewById(R.id.delete_notification);
deleteNotificationBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
deleteNotification();
}
});
Le projet sera très bientôt disponible en téléchargement.
Aucun commentaire:
Enregistrer un commentaire