Flutter 如何移除应用在通知栏中的1小时以上旧通知?
实现方案
针对Android 8及以上系统,你可以通过以下步骤仅移除留存超过1小时的旧通知,不用全量清空通知栏:
核心实现逻辑
你可以直接用常用的flutter_local_notifications通知库完成需求,无需单独对接原生通道:
- 该库提供了
getActiveNotifications()方法,Android 8及以上系统调用后可返回当前应用在通知栏的所有活跃通知 - 每个返回的通知实例携带
postTime字段,对应通知推送到系统栏的时间戳(单位:毫秒) - 遍历所有活跃通知,筛选出留存时长超过1小时的通知,单独调用取消接口移除即可
代码示例
import 'package:flutter/foundation.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; // 初始化后的通知实例,你发通知应该已经用到了这个对象 final FlutterLocalNotificationsPlugin notificationsPlugin = FlutterLocalNotificationsPlugin(); Future<void> clearOutdatedNotifications() async { // 仅处理Android平台 if (defaultTargetPlatform != TargetPlatform.android) return; // 获取当前应用所有活跃通知 final List<ActiveNotification>? activeNotifications = await notificationsPlugin.getActiveNotifications(); if (activeNotifications == null || activeNotifications.isEmpty) return; // 当前时间戳,单位毫秒 final int nowTimestamp = DateTime.now().millisecondsSinceEpoch; // 1小时对应的毫秒数 const int oneHourMilliseconds = 3600 * 1000; for (final ActiveNotification item in activeNotifications) { final int? postTime = item.postTime; // 跳过时间异常的通知,仅移除留存超过1小时的通知 if (postTime == null || nowTimestamp - postTime <= oneHourMilliseconds) { continue; } // 单独移除指定通知,不会影响其他活跃通知 await notificationsPlugin.cancel(item.id, tag: item.tag); } }
定期触发清理
你可以根据自己的业务场景选择触发时机:
- 每次应用切到前台时调用一次清理方法
- 用定时任务每隔30分钟/1小时在后台调用一次清理方法
注意事项
- 不需要额外申请任何系统权限,Android默认允许应用管理自己发送的通知
- 如果你的通知设置了分组或渠道,以上逻辑也可以正常匹配,不会误删其他通知
- 低于Android 8的系统调用
getActiveNotifications会返回空值,因为你所有设备都是Android 8及以上,无需额外做兼容处理
内容的提问来源于stack exchange,提问作者Shehan DMG
相关产品推荐
相关产品推荐

