web-dev-qa-db-fra.com

Comment utiliser exactement Notification.Builder

J'ai constaté que j'utilise une méthode obsolète pour les noficitations (notification.setLatestEventInfo ())

Il est dit d'utiliser Notification.Builder.

  • Comment l'utiliser?

Lorsque j'essaie de créer une nouvelle instance, il me dit:

Notification.Builder cannot be resolved to a type
98
Saariko

This est dans l'API 11, donc si vous développez pour une version antérieure à la version 3.0, vous devriez continuer à utiliser l'ancienne API.

Mise à jour : la classe NotificationCompat.Builder a été ajoutée au Support Package afin que nous puissions l'utiliser pour prendre en charge les API de niveau v4 et supérieur:

http://developer.Android.com/reference/Android/support/v4/app/NotificationCompat.Builder.html

86
Femi

Notification.Builder API 11 ou NotificationCompat.Builder API 1

Ceci est un exemple d'utilisation.

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);
151
Rabi

en plus de la réponse sélectionnée, voici un exemple de code pour le NotificationCompat.Builder classe de trucs source :

// Add app running notification  

    private void addNotification() {



    NotificationCompat.Builder builder =  
            new NotificationCompat.Builder(this)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setContentTitle("Notifications Example")  
            .setContentText("This is a test notification");  

    Intent notificationIntent = new Intent(this, MainActivity.class);  
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
            PendingIntent.FLAG_UPDATE_CURRENT);  
    builder.setContentIntent(contentIntent);  

    // Add as notification  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.notify(FM_NOTIFICATION_ID, builder.build());  
}  

// Remove notification  
private void removeNotification() {  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.cancel(FM_NOTIFICATION_ID);  
}  
70
ANemati

Notification Builder est strictement pour Android API de niveau 11 et supérieur (Android 3.0 et supérieur).

Par conséquent, si vous ne ciblez pas les tablettes Honeycomb, vous ne devez pas utiliser le générateur de notifications, mais plutôt suivre les méthodes de création de notifications plus anciennes, telles que celle-ci: exemple .

4
Ye Myat Min

MISE À JOUR Android-N (mars-2016)

Veuillez visiter le lien Notifications Updates pour plus de détails.

  • Réponse directe
  • Notifications groupées
  • Des vues personnalisées

Android N vous permet également d’associer des notifications similaires pour qu’elles apparaissent sous la forme d’une notification unique. Pour rendre cela possible, Android N utilise la méthode NotificationCompat.Builder.setGroup()] existante. Les utilisateurs peuvent développer chacune des notifications et effectuer des actions telles que répondre et ignorer chaque notification, individuellement à partir de l'ombre de notification.

Il s'agit d'un exemple préexistant qui montre un service simple qui envoie des notifications à l'aide de NotificationCompat. Chaque conversation non lue d’un utilisateur est envoyée sous forme de notification distincte.

Cet exemple a été mis à jour pour tirer parti des nouvelles fonctionnalités de notification disponibles dans Android N.

exemple de code .

3
Amit Vaghela

J'avais un problème de création de notifications (uniquement en développement pour Android 4.0+). Ce lien m'a montré exactement ce que je faisais mal et a déclaré ce qui suit:

Required notification contents

A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()

Fondamentalement, il me manquait l'un d'entre eux. Juste comme base pour résoudre ce problème, assurez-vous d’avoir au moins tout cela. Espérons que cela sauvera un autre mal de tête à quelqu'un d'autre.

2
Nlinscott

J'ai utilisé

Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
1
Nilesh Panchal

Cela fonctionne même dans API 8, vous pouvez utiliser ce code:

 Notification n = 
   new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe), 
System.currentTimeMillis());

PendingIntent i=PendingIntent.getActivity(this, 0,
             new Intent(this, NotifyActivity.class),
                               0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;

// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr = 
   (NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);

Ou je suggère de suivre un excellent tutoriel à ce sujet

1
dondondon

Au cas où cela aiderait quelqu'un ... J'avais beaucoup de difficulté à configurer les notifications à l'aide du package de support lors du test par rapport à une API plus récente. Je pouvais les amener à travailler sur le nouvel appareil, mais j'obtiendrais un test d'erreur sur l'ancien appareil. Ce qui a finalement fonctionné pour moi a été de supprimer toutes les importations liées aux fonctions de notification. En particulier, NotificationCompat et TaskStackBuilder. Il semble que lors de la configuration de mon code au début, les importations ont été ajoutées à partir de la nouvelle version et non du support. Ensuite, lorsque j'ai voulu implémenter ces éléments ultérieurement dans Eclipse, je n'ai pas été invité à les importer à nouveau. J'espère que cela a du sens et que cela aide quelqu'un d'autre à sortir :)

1
snatr

Exemple autonome

Même technique que dans cette réponse mais:

  • autonome: copier coller et il va compiler et exécuter
  • avec un bouton permettant de générer autant de notifications que vous le souhaitez et de jouer avec les ID d'intention et de notification

La source:

import Android.app.Activity;
import Android.app.Notification;
import Android.app.NotificationManager;
import Android.app.PendingIntent;
import Android.content.Context;
import Android.content.Intent;
import Android.graphics.Color;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.Button;

public class Main extends Activity {
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("click me");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Notification notification = new Notification.Builder(Main.this)
                        /* Make app open when you click on the notification. */
                        .setContentIntent(PendingIntent.getActivity(
                                Main.this,
                                Main.this.i,
                                new Intent(Main.this, Main.class),
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setContentTitle("title")
                        .setAutoCancel(true)
                        .setContentText(String.format("id = %d", Main.this.i))
                        // Starting on Android 5, only the alpha channel of the image matters.
                        // https://stackoverflow.com/a/35278871/895245
                        // `Android.R.drawable` resources all seem suitable.
                        .setSmallIcon(Android.R.drawable.star_on)
                        // Color of the background on which the alpha image wil drawn white.
                        .setColor(Color.RED)
                        .build();
                final NotificationManager notificationManager =
                        (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(Main.this.i, notification);
                // If the same ID were used twice, the second notification would replace the first one. 
                //notificationManager.notify(0, notification);
                Main.this.i++;
            }
        });
        this.setContentView(button);
    }
}

Testé dans Android 22.

          // This is a working Notification
       private static final int NotificID=01;
   b= (Button) findViewById(R.id.btn);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Notification notification=new       Notification.Builder(MainActivity.this)
                    .setContentTitle("Notification Title")
                    .setContentText("Notification Description")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
            NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            notification.flags |=Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(NotificID,notification);


        }
    });
}
0
Manoj Perumarath