Notifications

Une « notification » sous Android permet d’avoir une information persistante en dehors de son application. Par exemple, un service peut signaler une information via un Toast cf. la page Service. Le problème est que cette information est éphémère.

A) Création d’une notification :

Un objet Notification  doit posséder obligatoirement les propriétés suivantes :

     NotificationCompat.Builder builder =  
         new NotificationCompat.Builder(this)  
             .setSmallIcon(R.drawable.icon)  
             .setContentTitle("Message")  
             .setContentText("Titre");  

Des options peuvent être ajoutées telle la vibration et le son :

             .setVibrate(new long[]{1000, 1000})  
             .setSound(Settings.System.DEFAULT_NOTIFICATION_URI);  

La liste des options est .

B) Actions sur click :

Pour gérer le click sur la notification on utilise un Pending Intent :

     Intent notificationIntent = new Intent(this, MainActivity.class);  
     PendingIntent contentIntent = PendingIntent.getActivity(this, <<Numero de la notif>>, notificationIntent,  
         PendingIntent.FLAG_UPDATE_CURRENT);  
     builder.setContentIntent(contentIntent);  

Ici, on lance l’application « mainActivity ». Pour passer des valeurs à cette application (pour qu’elle exécute des tâches en fonction de la notification) utilisez les extras. Les valeurs du Flag du PendingIntent peuvent être :

in FLAG_CANCEL_CURRENTFlag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.
int FLAG_IMMUTABLEFlag indicating that the created PendingIntent should be immutable.
int FLAG_NO_CREATEFlag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it.
int FLAG_ONE_SHOTFlag indicating that this PendingIntent can be used only once.
int FLAG_UPDATE_CURRENTFlag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

C) Ajout de la notification :

     NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
     manager.notify(<<Numero Notification>>, builder.build());  

Pour que la notification efface la précédente, utilisez le même Numero de notification, sinon utilisez un numéro incrémental.

D) Passage de paramètres :

Ajout d’un extra dans l’intent

     Intent notificationIntent = new Intent(this, MainActivity.class);  
     notificationIntent.putExtra("URL", sUrl);  

Récupération dans l’activité « MainActivity » lors du click sur la notification se fera selon :

     Intent addIntent= getIntent(); // gets the previously created intent  
     String sUrlDetail = addIntent.getStringExtra("URL"); // will return "parameterValue"  
     Log.d("URL_DETAIL","=>"+sUrlDetail);  

E) Suppression de la notification :

 private void deleteNotification(int id_Notif, Context ctx){  
   final NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);  
   //la suppression de la notification se fait grâce à son ID  
   notificationManager.cancel(id_Notif);  
 }  

F) Gestion du click et suppression avec paramètres son et vibration :

Placez dans un service la fonction suivante :

  private void addNotification(String sIdAnn, String sUrlAnn, String sTitAnn, String sResuAnn,  
                  Boolean bVibre, Boolean bSon, Bitmap image) {  
     //-- Définition de la notification  
     NotificationCompat.Builder notif = new NotificationCompat.Builder(ctx);  
     notif.setSmallIcon(R.drawable.icon);  
     //notif.setLargeIcon(image)  
     notif.setContentTitle(sTitAnn);  
     notif.setContentText(sResuAnn);  
     if (bSon)  
       notif.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);  
     if (bVibre)  
       notif.setVibrate(new long[]{1000, 1000});  
     //notif.setAutoCancel(true); -> Supprime après le click sur la notif  
     //-- Intent pour action si click sur la notif  
     //-- avec Paramétres à passer  
     Intent notificationIntent = new Intent(this, MainActivity.class);  
     notificationIntent.putExtra("URL", sUrlAnn);  
     notificationIntent.putExtra("NUMANN", sIdAnn);  
     //  
     try {  
       nNbAnnonce = Integer.parseInt(sIdAnn);  
     } catch (NumberFormatException nfe) {  
       Log.d("ERROR", "Could not parse " + nfe);  
     }  
     PendingIntent contentIntent = PendingIntent.getActivity(this, nNbAnnonce, notificationIntent,  
         PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);  
     notif.setContentIntent(contentIntent);  
     //-- Ajout de l'intent sur suppression de la notification  
     Intent DeleteIntent = new Intent(this, MainActivity.class);  
     DeleteIntent.putExtra("DELETE", true);  
     DeleteIntent.putExtra("NUMANN", sIdAnn);  
     PendingIntent deleteIntent = PendingIntent.getActivity(this, nNbAnnonce, DeleteIntent,  
        0);  
     notif.setDeleteIntent(deleteIntent);  
     //-- Ajout de la notification  
     NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
     manager.notify(nNbAnnonce, notif.build());  
   }  
Et dans l'activité principale :
 Intent addIntent = getIntent(); // gets the previously created intent  
     sUrlDetail = addIntent.getStringExtra("URL");  
     sNumAnn  = addIntent.getStringExtra("NUMANN");  
     bDeleted  = addIntent.getBooleanExtra("DELETE", false);  
     Log.d("PARAM_NUM_ANN","=>"+sNumAnn);  
     Log.d("PARAM_URL_DETAIL", "=>" + sUrlDetail);  
     Log.d("PARAM_DELETE", "=>" + bDeleted);  
     if (sUrlDetail != null) { etc....  

G) Ajout d’une image dans la notification :

Redimensionner le Bitmap :

 Resources res= getResources();  
 int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height);  
 int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width);  
 bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);  

Le placer dans le buider :

notif.setLargeIcon(image);

H) Divers :

//-- hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;

Pour gérer l'appel de l'application, ajouter dans le manifest le type de tâche souhaitée, exemple "single top" =
<activity android:name=".MainActivity" android:launchMode="singleTop">
cf : https://www.mobomo.com/2011/06/android-understanding-activity-launchmode/

Références :

http://nbenbourahla.developpez.com/tutoriels/java/android_notification/

http://developer.android.com/training/notify-user/build-notification.html

http://www.tutorialspoint.com/android/android_notifications.htm

http://mrigaen.blogspot.fr/2014/03/the-all-important-setdeleteintent-for.html

Votre commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l’aide de votre compte WordPress.com. Déconnexion /  Changer )

Image Twitter

Vous commentez à l’aide de votre compte Twitter. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur la façon dont les données de vos commentaires sont traitées.

Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories
%d blogueurs aiment cette page :