Android Notification意图清除它自己

Joh*_*ohn 29 notifications android android-intent

我已经阅读了很多关于如何创建通知消息的示例.我想要实现的是,因为通知将由小部件执行,我希望在用户点击它时点击通知意图自我清除.我没有要返回的活动.我的目的通知只是明确通知,没有别的.那么只是清除/取消自己的意图代码是什么呢?下面的代码是由按钮启动的活动(不包括按钮代码),通知将由后台服务启动.

CharSequence title = "Hello";
CharSequence message = "Hello, Android!";
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Notification notification = new Notification(R.drawable.icon,"A New Message!",System.currentTimeMillis());

notification.defaults=Notification.FLAG_ONLY_ALERT_ONCE+Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, AndroidNotifications.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);

notification.setLatestEventInfo(AndroidNotifications.this, title,message, pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
Run Code Online (Sandbox Code Playgroud)

谢谢

Pen*_*m10 74

查看FLAG_AUTO_CANCEL

如果在用户单击通知时应取消通知,则应将位按位进入应该设置的标志字段.

编辑:

notification.flags |= Notification.FLAG_AUTO_CANCEL;
Run Code Online (Sandbox Code Playgroud)

  • 你的代码使用了错误(puts defaults字段),你需要按位或在flags字段中这样:`notification.flags | = Notification.FLAG_AUTO_CANCEL;` (17认同)
  • 谢谢notification.flags | = Notification.FLAG_AUTO_CANCEL; 工作. (2认同)

小智 19

在notification.flags中设置标志而不是notification.defaults.

例:

notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
Run Code Online (Sandbox Code Playgroud)


san*_*one 10

如果你正在使用NotificationCompat.Builder(的一部分android.support.v4),那么只需调用它的对象的方法setAutoCancel

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);
Run Code Online (Sandbox Code Playgroud)

有些人报告说这setAutoCancel()对他们不起作用,所以你也可以尝试这种方式

builder.build().flags |= Notification.FLAG_AUTO_CANCEL;
Run Code Online (Sandbox Code Playgroud)


ian*_*sme 1

我认为这样做的唯一方法就是让你的Notification观点Intent有背景Service。当此服务启动时,它将清除给定的Notificationusing NotificationManager.cancel(int id)。然后它Service会自行停止。它不漂亮,也不容易实现,但我找不到任何其他方法。