web-dev-qa-db-fra.com

Comment créer une notification avec NotificationCompat.Builder?

J'ai besoin de créer une notification simple qui sera affichée dans la barre de notification avec le son et l'icône si possible? J'en ai aussi besoin pour être compatible avec Android 2.2. J'ai donc constaté que NotificationCompat.Builder fonctionnait avec toutes les API supérieures à 4. S'il existe une meilleure solution, n'hésitez pas à le mentionner.

49
Vladimir

Le NotificationCompat.Builder est le moyen le plus simple de créer Notifications sur toutes les versions d'Android. Vous pouvez même utiliser les fonctionnalités disponibles avec Android 4.1. Si votre application fonctionne sur des appareils dotés d'Android> = 4.1, les nouvelles fonctionnalités seront utilisées. Si elles sont exécutées sous Android <4.1, la notification sera une simple notification ancienne.

Pour créer une notification simple, faites (voir Guide de l'API Android sur Notifications ):

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setContentIntent(pendingIntent); //Required on Gingerbread and below

Vous devez définir au moins smallIcon, contentTitle et contentText. Si vous en manquez une, la notification ne s'affichera pas.

Attention: Sur le pain d'épice et au-dessous, vous devez définir l'intention de contenu, sinon une IllegalArgumentException sera lancée.

Pour créer une intention qui ne fait rien, utilisez:

final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Vous pouvez ajouter du son via le générateur, c’est-à-dire un son de RingtoneManager:

mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

La notification est ajoutée à la barre via le NotificationManager:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());
121
thaussma

Exemple de travail:

    Intent intent = new Intent(ctx, HomeActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder b = new NotificationCompat.Builder(ctx);

    b.setAutoCancel(true)
     .setDefaults(Notification.DEFAULT_ALL)
     .setWhen(System.currentTimeMillis())         
     .setSmallIcon(R.drawable.ic_launcher)
     .setTicker("Hearty365")            
     .setContentTitle("Default notification")
     .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
     .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
     .setContentIntent(contentIntent)
     .setContentInfo("Info");


    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, b.build());
23
Sumoanand

Je fais cette méthode et fonctionne bien. (testé sous Android 6.0.1)

public void notifyThis(String title, String message) {
    NotificationCompat.Builder b = new NotificationCompat.Builder(this.context);
    b.setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.favicon32)
            .setTicker("{your tiny message}")
            .setContentTitle(title)
            .setContentText(message)
            .setContentInfo("INFO");

    NotificationManager nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(1, b.build());
}

Notification en profondeur

CODE

Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.your_notification_icon)
                        .setContentTitle("Notification Title")
                        .setContentText("Notification ")
                        .setContentIntent(pendingIntent );

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

Connaissance approfondie

Notification peut être construit en utilisant Notification. Classes Builder ou NotificationCompat.Builder.
Toutefois, si vous souhaitez une compatibilité ascendante, vous devez utiliser la classe NotificationCompat.Builder, car elle fait partie de v4 Support library , car elle prend en charge de lourdes tâches pour fournir un aspect et des fonctionnalités cohérents à Notification for API 4 et versions ultérieures. 

Propriétés de notification de base

Une notification a 4 propriétés principales (3 propriétés d'affichage de base + propriété d'action 1 clic)

  • Petite icône
  • Titre
  • Texte
  • Bouton clic événement (clic événement lorsque vous appuyez sur la notification) 

L'événement clic sur le bouton est rendu facultatif sur Android 3.0 et supérieur. Cela signifie que vous pouvez créer votre notification en utilisant uniquement les propriétés d'affichage si votre minSdk cible Android 3.0 ou une version ultérieure. Mais si vous souhaitez que votre notification soit exécutée sur des appareils plus anciens qu'Android 3.0, vous devez indiquer l'événement Click, sinon vous verrez apparaître IllegalArgumentException. 

Affichage de notification

Les notifications sont affichées en appelant la méthode notify () de la classe NotificationManger 

paramètres notify ()

Il existe deux variantes disponibles pour la méthode de notification 

notify(String tag, int id, Notification notification)

ou 

notify(int id, Notification notification)

la méthode notify utilise un identifiant entier pour identifier votre notification de manière unique. Toutefois, vous pouvez également fournir une balise String facultative pour une identification plus poussée de votre notification en cas de conflit. 

Ce type de conflit est rare, mais disons que vous avez créé une bibliothèque et d'autres développeurs utilisent votre bibliothèque. Maintenant, ils créent leur propre notification et en quelque sorte votre notification et d'autres développeurs notification id est identique, alors vous ferez face à un conflit.

Notification après API 11 (Plus de contrôle)

API 11 fournit un contrôle supplémentaire sur le comportement de notification 

  • Renvoi de notification
    Par défaut, si un utilisateur appuie sur une notification, il effectue l'événement de clic attribué mais ne nettoie pas la notification. Si vous souhaitez que votre notification soit effacée, vous devez alors ajouter ceci. 

    mBuilder.setAutoClear (true);

  • Empêcher l'utilisateur de rejeter la notification
    Un utilisateur peut également rejeter la notification en la glissant. Vous pouvez désactiver ce comportement par défaut en l'ajoutant lors de la création de votre notification. 

    mBuilder.setOngoing (true);

  • Positionnement de la notification
    Vous pouvez définir la priorité relative de votre notification en 

    mBuilder.setOngoing (int pri);

Si votre application fonctionne avec une API inférieure à 11, votre notification fonctionnera sans les fonctionnalités supplémentaires mentionnées ci-dessus. C’est l’avantage de choisir NotificationCompat.Builder plutôt que Notification.Builder.

Notification après API 16 (Plus informative)

Avec l'introduction de l'API 16, de nombreuses nouvelles fonctionnalités ont été apportées aux notifications.
La notification peut être beaucoup plus informative.
Vous pouvez ajouter un bigPicture à votre logo. Supposons que vous receviez maintenant un message d'une personne avec le mBuilder.setLargeIcon (bitmap bitmap), vous pouvez afficher la photo de cette personne. Donc, dans la barre d'état, vous verrez l'icône lorsque vous faites défiler, vous verrez la photo de la personne à la place de l'icône. Il y a aussi d'autres fonctionnalités 

  • Ajouter un compteur dans la notification
  • Message de téléscripteur lorsque vous voyez la notification pour la première fois
  • Notification extensible
  • Notification multiligne et ainsi de suite
2
Rohit Singh

moyen simple de faire des notifications

 NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher) //icon
            .setContentTitle("Test") //tittle
            .setAutoCancel(true)//swipe for delete
            .setContentText("Hello Hello"); //content
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, builder.build()
    );
1

Afficher la notification dans Android 8.0

@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

  public void show_Notification(){

    Intent intent=new Intent(getApplicationContext(),MainActivity.class);
    String CHANNEL_ID="MYCHANNEL";
    NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"name",NotificationManager.IMPORTANCE_LOW);
    PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
    Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
            .setContentText("Heading")
            .setContentTitle("subheading")
            .setContentIntent(pendingIntent)
            .addAction(Android.R.drawable.sym_action_chat,"Title",pendingIntent)
            .setChannelId(CHANNEL_ID)
            .setSmallIcon(Android.R.drawable.sym_action_chat)
            .build();

    NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    notificationManager.notify(1,notification);


}
1
Ankush Shrivastava

Vous pouvez essayer ce code cela fonctionne très bien pour moi:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);

    Intent i = new Intent(noti.this, Xyz_activtiy.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0);

    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
    mBuilder.setWhen(20000);
    mBuilder.setTicker("Ticker");
    mBuilder.setContentInfo("Info");
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.home);
    mBuilder.setContentTitle("New notification title");
    mBuilder.setContentText("Notification text");
    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(2,mBuilder.build());
1
Rohit Lalwani

Utilisez ce code

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());
0