如何查询已调度的本地通知数量?求相关实现示例
查看已调度本地通知数量的实现方案
iOS 平台
iOS 没有直接提供获取已调度本地通知总数的API,但可以通过UNUserNotificationCenter(iOS 10+)实现统计:
- 调用
getPendingNotificationRequests(completionHandler:)方法,获取当前App所有待调度的通知请求数组,数组的count属性就是已调度通知的数量。
示例代码:import UserNotifications UNUserNotificationCenter.current().getPendingNotificationRequests { requests in let scheduledCount = requests.count print("已调度的本地通知数量:\(scheduledCount)") } - 注意:此方法仅能获取当前App发起的待发送通知,无法获取系统或其他App的调度通知。
Android 平台
Android 需根据通知的调度方式选择对应统计方案:
- 若用
WorkManager调度通知任务:可通过WorkManager.getWorkInfosByTag()或getWorkInfosForUniqueWork()获取待执行任务列表,统计其中属于通知任务的数量。 - 若用
AlarmManager结合PendingIntent:由于AlarmManager无直接查询所有PendingIntent的API,需自行通过本地存储(如SharedPreferences、Room)维护调度记录——调度通知时存入任务ID,取消时移除,通过查询存储记录数得到已调度数量。
示例(基于SharedPreferences):// 调度通知时记录ID val sharedPref = getSharedPreferences("NotificationScheduler", Context.MODE_PRIVATE) val editor = sharedPref.edit() val notificationIds = sharedPref.getStringSet("scheduledIds", mutableSetOf()) ?: mutableSetOf() notificationIds.add("unique_notification_id") editor.putStringSet("scheduledIds", notificationIds) editor.apply() // 获取已调度数量 val scheduledCount = sharedPref.getStringSet("scheduledIds", mutableSetOf())?.size ?: 0
内容的提问来源于stack exchange,提问作者matthias_code
相关产品推荐
相关产品推荐

