Android 通知用户更新或移除通知

原文地址:http://android.xsoftlab.net/training/notify-user/managing.html#Removing

当需要在不同时段发布同一事件类型的通知时,应当避免创建新的通知。相反的,应当考虑更新原有的通知,比如更改通知的某些值或者添加一些信息给通知。

下面的部分描述了如何更新通知以及如何移除通知。

修改通知

为了设置通知是可以更新的,需要在发布通知时由NotificationManager.notify(ID, notification)方法指定该通知的ID。为了更新这条通知,需要更新或者创建一个NotificationCompat.Builder对象,并由这个对象构建一个Notification对象,然后将这个通知对象以相同的ID发布出去。

下面的代码段演示了在事件发生时,一条通知将会被用来更新该事件的数目:

mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
    .setContentTitle("New Message")
    .setContentText("You've received new messages.")
    .setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
    mNotifyBuilder.setContentText(currentText)
        .setNumber(++numMessages);
    // Because the ID remains unchanged, the existing notification is
    // updated.
    mNotificationManager.notify(
            notifyID,
            mNotifyBuilder.build());
...

移除通知

在以下事件发生时,通知将会从通知栏中移除:

用户移除了该通知或者使用了”Clear All”功能(如果通知是可移除的话)。

用户点击了通知,这条通知在创建时使用了setAutoCancel(false)方法(false是默认属性)。

通过调用cancel()方法并指定该通知的ID。这个方法还可以移除进行中的通知。

通过调用cancelAll()方法,将已经发布的所有通知移除。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值