Notification setAutoCancel(true) doesn't work

こ雲淡風輕ζ 提交于 2019-12-21 06:49:22

问题


I'm trying to show a notification that is removed when the user taps on it. I'm using the NotificationCompat class to build my notification and I call setAutoCancel(true) on my builder. This is the piece of code:

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());

The notification is correctly added but when I tap on it nothing happens! What am I doing wrong?


回答1:


Using setContentIntent should solve your problem:

.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));

In your example:

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());

Often you might want to direct the user to the relevant content and so might replace 'new Intent()' with something else.

I uploaded a demo to github.




回答2:


I know an answer has already been accepted, but I had the same problem with a different solution so I will share it here.

For me, I was using the same NotificationCompat.Builder object to create a notification which called setOngoing(true). This was for an upload progress notification which should not be removed while working.

Anyways, after the task was complete, I called setAutoCancel(true) but the notification was still not swiping away. What I had to do also was call setOngoing(false).

It seems pretty obvious now, but it might save someone else some time in the future.



来源:https://stackoverflow.com/questions/15033316/notification-setautocanceltrue-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!