我正在尝试显示当用户点击它时删除的通知。
我正在使用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());
通知已正确添加但当我点击它时没有任何反应!我做错了什么?
答案 0 :(得分:50)
使用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()”替换为其他内容。
我将demo上传到github。
答案 1 :(得分:21)
我知道答案已经被接受了,但是我遇到了同样的问题,所以我会在这里分享。
对我来说,我使用相同的NotificationCompat.Builder
对象来创建一个名为setOngoing(true)
的通知。这是针对上传进度通知,在工作时不应删除。
无论如何,在任务完成后,我打电话给setAutoCancel(true)
,但通知仍然没有消失。我还要做的就是打电话setOngoing(false)
。
现在看起来非常明显,但未来一段时间可能会拯救别人。