28

我试图显示当用户点击它时删除的通知。我正在使用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());

通知已正确添加,但是当我点击它时没有任何反应!我究竟做错了什么?

4

2 回答 2

57

使用 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。

于 2013-03-19T16:51:39.857 回答
30

我知道答案已经被接受,但是我在使用不同的解决方案时遇到了同样的问题,所以我将在这里分享。

对我来说,我使用同一个NotificationCompat.Builder对象来创建一个名为setOngoing(true). 这是一个上传进度通知,在工作时不应删除。

无论如何,任务完成后,我打电话,setAutoCancel(true)但通知仍然没有滑动。我必须做的也是调用setOngoing(false)

现在看起来很明显,但它可能会在未来为其他人节省一些时间。

于 2014-04-21T21:01:39.077 回答