Tutoriel Android: Comment créer des notifications ? 09.jan
Bonjour à tous pour ce nouveau tutoriel ! Aujourd’hui nous allons apprendre comment faire pour notifier des informations à l’utilisateur.
Pour cela nous avons plusieurs moyens:
- Les alertDialogs
- Les notifications
- Les Toasts
Je vais vous détailler tout cela dans ce tutoriel.
Je vais commencer par les alertDialogs:
Nous allons commencer par créer l’interface:
Nous allons créer une Activity:
package fr.thibaultkoprowski.android.notifications;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Notification extends Activity {
// Id de notre boite de dialog
private static final int ALERT_DIALOG = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// On défini le listener lié au boutton qui affiche une boite de dialogue
((Button)findViewById(R.id.bt_alert_dialog)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// On affiche l'AlertDialog
showDialog(ALERT_DIALOG);
}
});
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch(id) {
// Ici on peut définir plusieurs boites de dialogue diférentes
case ALERT_DIALOG:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// On définit le message à afficher dans la boite de dialogue
builder.setMessage("Etes vous sûr de vouloir quitter l'application")
.setCancelable(false)
.setPositiveButton("Oui", new DialogInterface.OnClickListener() {
// On définit l'action pour le oui
public void onClick(DialogInterface dialog, int id) {
// On ferme l'application
Notification.this.finish();
}
})
.setNegativeButton("Non", new DialogInterface.OnClickListener() {
// On définit l'action pour le bouton non
public void onClick(DialogInterface dialog, int id) {
// On retire la boite de dialogue
dialog.cancel();
}
});
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
}
Lorsque vous appuyez sur le bouton, vous avez une boite de dialogue qui s’ouvre.
Nous allons maintenant passer aux Toast. Un toast est un message qui s’affiche temporairement sur l’écran. Comme ci-dessous:
Nous devons ajouter le code suivant dans le fichier d’interface XML:
Ainsi que le code suivant dans la méthode onCreate():
((Button)findViewById(R.id.bt_toast)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Voici comment afficher un toast
// Le premier paramètre correspond au context de l'application
// Le deuxième correspond au texte à afficher
// Le troisième est la constante de durée il y a SHORT ET LONG de disponible
Toast.makeText(getApplicationContext(), "Voici un toast", Toast.LENGTH_LONG).show();
}
});
Désormais, lorsque vous appuyez sur le bouton, vous avez un joli petit Toast ! ![]()
Ceci peut être très intéressant pour informer l’utilisateur d’un évènement ou autre.
Passons aux notifications !
Comme précédemment, nous ajoutons un bouton au fichier XML d’interface:
Ensuite nous ajoutons le listener dans la méthode onCreate:
((Button)findViewById(R.id.bt_notif)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nm = (NotificationManager) context.getSystemService(ns);
nm.cancel(R.string.app_name);
// On fixe l'icône
int icon = R.drawable.icon;
// On défini quand on veut afficher la notification
long when = System.currentTimeMillis();
// On définit le titre
CharSequence contentTitle = "Titre de la notification";;
// On définit le contenu du texte de la notification
CharSequence contentText = "Voici le contenu de la notification";
Notification notificationActivity = new Notification(icon, contentTitle, when);
// On peut ajouter un intent executé lors du click sur la notification
// Ici une page web ouvrant mon site ^^
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.thibault-koprowski.fr"));
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
notificationActivity.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
nm.notify(R.string.app_name, notificationActivity);
}
});
Et voila! nous avons fais le tour !
N’oubliez pas de rajouter l’autorisation dans le fichier de manifest pour l’accès à Internet !
A bientôt dans un prochain tutoriel pour Android
!
Source du projet sur les notifications

#1 by Hannibal (1 year ago):