我想更新通知数据,但我发现的唯一方法是用相同的ID启动一个新的。
问题是如果原文取消,我不想再提一个。 有没有办法告诉通知是否可见或取消? 或者只有在通知存在时才更新通知?
这是我解决它的方法:
private boolean isNotificationVisible() { Intent notificationIntent = new Intent(context, MainActivity.class); PendingIntent test = PendingIntent.getActivity(context, MY_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE); return test != null; }
这是我如何生成通知:
/** * Issues a notification to inform the user that server has sent a message. */ private void generateNotification(String text) { int icon = R.drawable.notifiaction_icon; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, text, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, MainActivity.class); // set intent so it does not start a new activity //notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, MY_ID, notificationIntent, 0); notification.setLatestEventInfo(context, title, text, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; //PendingIntent.FLAG_ONE_SHOT notificationManager.notify(MY_ID, notification); }
萨拉姆。 如果您使用API >= 23
可以使用此方法获取主动通知:
StatusBarNotification[] notifications = mNotificationManager.getActiveNotifications(); for (StatusBarNotification notification : notifications) { if (notification.getId() == 100) { // Do something. } }
我认为你可以使用Notification
类的deleteIntent 。
我记得在我的一个应用程序中,当通知被取消或通知盘被清除时,我用它来激活广播(自定义广播)。
deleteIntent
的替代方法如下,在我的应用程序中certificate是有益的:
基本上,你创build一个意图与您的通知,启动一个IntentService (或任何其他服务),并在onHandleIntent
你可以设置一个标志,指出是否通知是积极的。
当用户点击通知( contentIntent )和/或用户从列表中清除( deleteIntent )时,您可以设置此意图。
为了说明这一点,下面是我在自己的应用程序中所做的。 当build立通知我设置
Intent intent = new Intent(this, CleanupIntentService.class); Notification n = NotificationCompat.Builder(context).setContentIntent( PendingIntent.getActivity(this, 0, intent, 0)).build();
当通知被点击时,我的CleanupIntentService
被启动,设置一个标志(在创build通知的服务中):
@Override public int onStartCommand(Intent intent, int flags, int startId) { super.onCreate(); // If removed, onHandleIntent is not called return super.onStartCommand(intent, flags, startId); } @Override protected void onHandleIntent(Intent intent) { OtherService.setNotificationFlag(false); }