You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter 如何移除应用在通知栏中的1小时以上旧通知?

实现方案

针对Android 8及以上系统,你可以通过以下步骤仅移除留存超过1小时的旧通知,不用全量清空通知栏:

核心实现逻辑

你可以直接用常用的flutter_local_notifications通知库完成需求,无需单独对接原生通道:

  1. 该库提供了getActiveNotifications()方法,Android 8及以上系统调用后可返回当前应用在通知栏的所有活跃通知
  2. 每个返回的通知实例携带postTime字段,对应通知推送到系统栏的时间戳(单位:毫秒)
  3. 遍历所有活跃通知,筛选出留存时长超过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:24:00