lundi 18 juin 2012

Les notifications sous Android

Le but de ce tutoriel est d’apprendre à utiliser les notifications sous Android et de prévenir les utilisateurs de vos applications d’un événement particulier ou interagir avec eux.
                                                           


Qu’est qu’une notification ?

Une notification est une indication qui s’affiche sur la barre qui se situe en haut d’un téléphone Android. Cette notification sert à prévenir un utilisateur de certains évènements, comme la récéption d’un message par exemple.
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 : 2.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 clique. 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 clique sur le bouton “Ajouter une notification”. Voici a quoi ressemble cette méthode :
private final void createNotification(){
   //Récupération du notification Manager
       final NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
       //Création de la notification avec spécification de l'icone de la notification et le texte qui apparait à la création de la notfication
       final Notification notification = new Notification(R.drawable.notification, notificationTitle, System.currentTimeMillis()); 
       //Definition de la redirection au moment du clique sur la notification. Dans notre cas la notification redirige vers notre application
       final PendingIntent pendingIntent = PendingIntent.getActivity(this0new Intent(this, TutoNotificationHomeActivity.class), 0);
       //Récupération du titre et description de la notfication
       final String notificationTitle = getResources().getString(R.string.notification_title);
       final String notificationDesc = getResources().getString(R.string.notification_desc);        
       //Notification & Vibration
       notification.setLatestEventInfo(this, notificationTitle, notificationDesc, pendingIntent);
       notification.vibrate = new long[] {0,200,100,200,100,200};
       notificationManager.notify(NOTIFICATION_ID, notification);
   }
Je vous met l’icone que j’ai utilisé pour la notifcation http://www.tutos-android.com/wp-content/uploads/2011/06/notification.png .




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>
                                                          

                                                          

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 clique
deleteNotificationBtn = (Button) findViewById(R.id.delete_notification);
 deleteNotificationBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
        deleteNotification();
        }
    });

Conclusion

En espérant que cet tutoriel vous aura aidé à comprendre comment fonctionne les notifications sous Android.
Share:

0 commentaires:

Enregistrer un commentaire

Contributeurs

Membres

free counters