通知setAutoCancel(true)不起作用

The*_*ind 24 notifications android click

我正在尝试显示当用户点击它时删除的通知.我正在使用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());
Run Code Online (Sandbox Code Playgroud)

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

sno*_*per 50

使用setContentIntent可以解决您的问题:

.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
Run Code Online (Sandbox Code Playgroud)

在你的例子中:

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());
Run Code Online (Sandbox Code Playgroud)

通常,您可能希望将用户定向到相关内容,因此可能会将"new Intent()"替换为其他内容.

我上传了一个演示到github.


JMR*_*ies 22

我知道答案已被接受,但我遇到了同样的问题,因此我将在此处分享.

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

无论如何,在任务完成后,我打电话,setAutoCancel(true)但通知仍然没有消失.我还要做的就是打电话setOngoing(false).

现在看起来很明显,但未来可能会节省一些时间.