Notification使用误区

本文介绍了如何使用NotificationManager和NotificationCompat.Builder来更新Android应用的通知。通过设置相同的ID并更新Notification的内容,可以实现在通知未被清除时进行更新,在已清除时重新创建的功能。文章还提醒了频繁更新通知可能带来的问题,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Updating notifications

To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(). To update this notification after you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously. If the previous notification is still visible, the system updates it from the contents of the Notification object. If the previous notification has been dismissed, a new notification is created instead.

Caution: The system applies a rate limit to updating notifications. If you post updates to a notification too frequently, the system may drop some notifications. Note: You can optionally call  setOnlyAlertOnce() to only turn on a notification sound, vibration, and ticker if the notification is not already showing.

The following snippet demonstrates a notification that is updated to reflect the number of events that have occurred. It stacks the notification, showing a summary:

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, CHANNEL_ID)
    .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());
...



=======================================

notification 更新一次就new 一次。。。不需要复用!!!!!!

否则会造成 TransactionTooLargeException   !!!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值