130

我希望在用户单击通知后关闭通知。我看到每个人都说要使用标志,但我在任何地方都找不到标志,因为我使用的是 NotificationCompat.Builder 类而不是 Notification 类。有人知道如何让她自己删除通知吗?
这是我设置通知时的代码:

NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("New Question")
            .setContentText("" + QuestionData.getAuthor().getUserName() + ": " + QuestionData.getQuestion() + "");

    Intent openHomePageActivity = new Intent("com.example.ihelp.HOMEPAGEACTIVITY");
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntent(openHomePageActivity);

    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);       

    mNotificationManager.notify(0, mBuilder.build());
4

5 回答 5

337

很简单,简单地调用这个:

mBuilder.setAutoCancel(true);

此外,虽然它不是真的必要,但如果你真的想使用FLAG_AUTO_CANCEL,只需在调用之前调用它mNotificationManager.notify

mBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL;
于 2013-03-27T17:00:59.870 回答
19

尝试这个....

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

 ..........
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.push_notify_icon)
            .setContentTitle("New Question!")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setAutoCancel(true).setContentText("" + QuestionData.getAuthor().getUserName() + ": " + QuestionData.getQuestion() + "");
mBuilder.setContentIntent(contentIntent);

    ..............        


mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(0, mBuilder.build());
于 2014-08-19T16:10:35.253 回答
12

这是通知:

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_calendar)
            .setContentTitle("My Firebase Push notification")
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent);

点击取消背后的关键是:

            .setAutoCancel(true)

我希望它能解决这个问题。

于 2018-08-26T06:19:36.893 回答
3

您可以在通知中添加标志:

http://developer.android.com/reference/android/app/Notification.html#FLAG_AUTO_CANCEL

这将在单击时将其关闭。

于 2013-02-27T19:42:52.470 回答
2

在 kotlin 中,您可以使用:

mBuilder.build().flags.and(Notification.FLAG_AUTO_CANCEL)
于 2019-04-15T10:12:46.720 回答