Comment rejeter une notification après avoir cliqué sur une action?

depuis API Niveau 16 (Jelly Bean), il est possible d'ajouter des actions à une notification avec

builder.addAction(iconId, title, intent);

mais lorsque j'ajoute une action à une notification et que l'action est pressée, la notification ne sera pas rejetée. Lorsque la notification elle-même est cliquée, elle peut être rejetée par

notification.flags = Notification.FLAG_AUTO_CANCEL;

ou

builder.setAutoCancel(true);

mais évidemment, cela n'a rien à voir avec les actions associées à la notification.

des indices? Ou est-ce que ça ne fait pas encore partie de L'API? Je n'ai pas trouvé quoi que ce soit.

111
demandé sur Sufian 2012-08-09 16:32:08

6 réponses

lorsque vous avez appelé notify sur le gestionnaire de notification vous lui avez donné un id - qui est l'id unique que vous pouvez utiliser pour y accéder plus tard (c'est du gestionnaire de notification:

notify(int id, Notification notification)

pour annuler, vous appelleriez:

cancel(int id)

avec la même identification. Donc, en gros, vous devez garder une trace de la carte d'identité ou peut-être mettre la carte d'identité dans un paquet que vous ajoutez à L'intention à l'intérieur du pendentif?

126
répondu Kaediil 2012-08-09 13:15:23

a trouvé que c'était un problème lors de l'utilisation de la notification Heads Up Display de Lollipop. Voir design guidelines . Voici le code complet (ish) à mettre en œuvre.

Jusqu'à maintenant, avoir un bouton "Rejeter" était moins important, mais maintenant c'est plus dans votre visage.

heads up notification

construction de la Notification

int notificationId = new Random().nextInt(); // just use a counter in some util class...
PendingIntent dismissIntent = NotificationActivity.getDismissIntent(notificationId, context);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setPriority(NotificationCompat.PRIORITY_MAX) //HIGH, MAX, FULL_SCREEN and setDefaults(Notification.DEFAULT_ALL) will make it a Heads Up Display Style
        .setDefaults(Notification.DEFAULT_ALL) // also requires VIBRATE permission
        .setSmallIcon(R.drawable.ic_action_refresh) // Required!
        .setContentTitle("Message from test")
        .setContentText("message")
        .setAutoCancel(true)
        .addAction(R.drawable.ic_action_cancel, "Dismiss", dismissIntent)
        .addAction(R.drawable.ic_action_boom, "Action!", someOtherPendingIntent);

// Gets an instance of the NotificationManager service
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

// Builds the notification and issues it.
notifyMgr.notify(notificationId, builder.build());

Activité de notification "1519150920

public class NotificationActivity extends Activity {

    public static final String NOTIFICATION_ID = "NOTIFICATION_ID";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(getIntent().getIntExtra(NOTIFICATION_ID, -1));
        finish(); // since finish() is called in onCreate(), onDestroy() will be called immediately
    }

    public static PendingIntent getDismissIntent(int notificationId, Context context) {
        Intent intent = new Intent(context, NotificationActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(NOTIFICATION_ID, notificationId);
        PendingIntent dismissIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return dismissIntent;
    }

}

AndroidManifest.xml (attributs requis pour empêcher SystemUI de se concentrer sur une pile arrière)

<activity
    android:name=".NotificationActivity"
    android:taskAffinity=""
    android:excludeFromRecents="true">
</activity>
56
répondu aaronvargas 2016-09-19 14:40:15

j'ai trouvé que lorsque vous utilisez les boutons d'action dans les notifications étendues, vous devez écrire du code supplémentaire et vous êtes plus contraint.

Vous devez annuler manuellement votre notification lorsque l'utilisateur clique sur un bouton d'action. La notification n'est annulée automatiquement pour l'action par défaut.

aussi si vous démarrez un récepteur de radiodiffusion à partir du bouton, le tiroir de notification ne se ferme pas.

j'ai fini créer une nouvelle activité de notification pour aborder ces questions. Cette activité intermédiaire sans aucune UI annule la notification et commence alors l'activité que je voulais vraiment commencer à partir de la notification.

j'ai posté un exemple de code dans un post connexe en cliquant sur les Actions de Notification Android ne ferme pas le tiroir de Notification .

15
répondu Vicki 2017-05-23 11:47:28

vous pouvez toujours cancel() le Notification de tout ce qui est invoqué par l'action (par exemple, dans onCreate() de l'activité liée au PendingIntent que vous fournissez à addAction() ).

5
répondu CommonsWare 2012-08-09 12:44:27

dans mon avis, l'utilisation d'un BroadcastReceiver est un moyen plus propre d'annuler une Notification:

Dans AndroidManifest.xml:

<receiver 
    android:name=.NotificationCancelReceiver" >
    <intent-filter android:priority="999" >
         <action android:name="com.example.cancel" />
    </intent-filter>
</receiver>

Dans le Fichier java:

Intent cancel = new Intent("com.example.cancel");
PendingIntent cancelP = PendingIntent.getBroadcast(context, 0, cancel, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Action actions[] = new NotificationCompat.Action[1];


NotificationCancelReceiver

public class NotificationCancelReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Cancel your ongoing Notification
    };
}
5
répondu Himanshu Khandelwal 2015-09-14 18:22:09

mettez juste cette ligne:

 builder.setAutoCancel(true);

et le code complet est:

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(android.R.drawable.ic_dialog_alert);
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
    builder.setContentIntent(pendingIntent);
    builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.misti_ic));
    builder.setContentTitle("Notifications Title");
    builder.setContentText("Your notification content here.");
    builder.setSubText("Tap to view the website.");
    Toast.makeText(getApplicationContext(), "The notification has been created!!", Toast.LENGTH_LONG).show();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    builder.setAutoCancel(true);
    // Will display the notification in the notification bar
    notificationManager.notify(1, builder.build());
0
répondu Hanisha 2018-03-13 13:14:55