通知的setAutoCancel(true)无效

32
我将尝试展示一种在用户点击后即可移除的通知。 我使用NotificationCompat类来构建我的通知,并在构建器上调用setAutoCancel(true)。以下是代码片段:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("title")
        .setAutoCancel(true)
        .setContentText("content");
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

通知已经成功添加,但是当我点击它时没有任何反应!我做错了什么?

通知一直停留在那里?当您滑动以解除它时会发生什么?您正在运行哪个设备和API版本? - Joe Malin
1
我正在Galaxy Nexsus上运行,API版本为4.2.2。如果我滑动通知,它会消失,但如果我只是轻触它,什么也不会发生。 - TheModularMind
2个回答

59
使用setContentIntent可以解决您的问题:
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));

在您的示例中:

NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("title")
        .setAutoCancel(true)
        .setContentText("content")
        .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

有时您可能希望将用户引导至相关内容,因此可能会使用其他方法替换“new Intent()”。

我在 github 上上传了一个演示


谢谢。尽管用户仍然可以通过滑动来清除通知。 - gatopeich
我发现这个方法可行,但可能会导致意外的结果:我还单独打开了contentIntent而不是从通知中打开。这可能会自动取消通知的声音(在moto g3上会,在Google Pixel上则不会)。 - jobbert
这也会关闭通知列表。如果有一种不关闭它的方法,那就更好了。 - Benur21

31

我知道已经有一个被接受的答案了,但是我遇到了不同的问题并找到了不同的解决方案,所以在这里分享一下。

对于我来说,我使用同一个NotificationCompat.Builder对象创建了一个通知,在其中调用了setOngoing(true)。这是用于显示上传进度的通知,应该在工作时不移除。

无论如何,任务完成后,我调用了setAutoCancel(true),但是通知仍然不能被滑动移除。我还需要调用setOngoing(false)

现在似乎很明显了,但它可能会节省其他人的时间。


setOngoing 是做什么用的? - IgorGanapolsky
对我来说没用 :-( - Pasquale Piccolo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接