Android 通知点击/滑动无法取消问题

5
我正在使用 startForeground(id, notification) 创建一个来自意图服务的通知。
Random r=new Random();
int id=r.nextInt(9999);

Builder notice2=new Notification.Builder(getApplicationContext())
    .setContentTitle(call.getName())
    .setAutoCancel(true)
    .setContentIntent(intent)
    .setContentText("content")
    .setSmallIcon(com.project.calltracker.R.drawable.ic_alert)
    .setLargeIcon(BitmapFactory.decodeResource(getResources(), com.project.calltracker.R.drawable.ic_logo));

startForeground(id, notice2.getNotification());

这里我设置了AutoCancel(true),但是当我点击通知时它没有消失?我真的很困惑。我已经尝试了几个小时的所有方法,但仍然没有成功!请帮忙!谢谢!

2
这个回答解决了你的问题吗?如何通过通知(滑动取消)或清除所有通知来取消前台服务? - Stypox
3个回答

12

我从另一篇帖子的答案中找到了答案。基本上只能有一个前台服务。使用startForeground()生成通知意味着只要此服务在运行,通知就无法被删除。

相反,使用NotificationManager.notify()仅生成通知。对此通知设置AutoCancel(true)将使其在滑动/点击时消失。

谢谢!


4
您可以像这样修改您的代码,以便在单击时取消通知
Random r=new Random();
int id=r.nextInt(9999);

Builder notice2=new Notification.Builder(getApplicationContext())
    .setContentTitle(call.getName())
    .setAutoCancel(true)
    .setContentIntent((PendingIntent.getActivity(getApplicationContext(), id, intent, PendingIntent.FLAG_CANCEL_CURRENT))
    .setContentText("content")
    .setSmallIcon(com.project.calltracker.R.drawable.ic_alert)
    .setLargeIcon(BitmapFactory.decodeResource(getResources(), com.project.calltracker.R.drawable.ic_logo));

startForeground(id, notice2.getNotification());

我使用了适当的标记设置,将简单的普通Intent替换为PendingIntent以取消当前Notification。以下是有关PendingIntent的一些信息链接:
  1. http://developer.android.com/reference/android/app/PendingIntent.html
  2. What is an Android PendingIntent?
希望这能帮到你。

谢谢您的建议!实际上我已经在使用Pending Intent了。很抱歉它没有包含在上面的代码中。但是仍然没有起作用。我发现真正的问题是因为我使用startForeground来生成通知,而不是NotificationManager.notify()。 - user1122549

2

当服务仍在前台时,AutoCancel不起作用。要允许通过滑动取消,必须调用stopForeground():

startForeground(id, notice2.getNotification());
stopForeground(false); //false - do not remove generated notification

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