我想更新通知数据,但是我发现的唯一方法是使用相同的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);
}
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
StatusBarNotification[] notifications = mNotificationManager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
if (notification.getId() == 100) {
// Do something.
}
}
onHandleIntent
中可以设置指示通知是否处于活动状态的标志。您可以将此意图设置为在用户点击通知(contentIntent)和/或从列表中将其清除(deleteIntent)时触发。为了说明这一点,这是我在自己的应用程序中所做的。建立通知时,我设置了
Intent intent = new Intent(this, CleanupIntentService.class);
Notification n = NotificationCompat.Builder(context).setContentIntent(
PendingIntent.getActivity(this, 0, intent, 0)).build();
点击通知时,启动我的CleanupIntentService
,并在创建通知的服务中设置一个标志:
@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);
}