如何在本地通知触发时向本地存储插入数据?
实现本地通知触发时自动写入本地数据库的方案
核心思路
要实现通知触发时无需打开应用也能写入数据库,关键是利用本地通知的触发回调机制,在回调中执行数据库插入操作,无需依赖应用前台运行。
分平台实现步骤
iOS平台
- 实现
UNUserNotificationCenterDelegate的userNotificationCenter(_:didReceive:withCompletionHandler:)方法,处理通知触发事件:func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 获取通知标识与触发时间 let notificationID = response.notification.request.identifier // 若需存储预设触发时间,可从通知userInfo中提取 let triggerTime = response.notification.trigger?.nextTriggerDate() ?? Date() // 执行本地数据库插入 let dbManager = LocalDBManager.shared dbManager.addNotificationRecord(id: notificationID, triggerTime: triggerTime) completionHandler() } - 说明:即便应用处于后台或未启动状态,只要用户授予通知权限,系统会唤醒该回调执行,完成数据库写入。
Android平台
- 自定义
BroadcastReceiver接收通知触发广播:class NotificationTriggerReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { context?.let { ctx -> // 从Intent中获取通知标识与预设触发时间 val notificationID = intent?.getStringExtra("NOTIFICATION_ID") ?: "" val presetTriggerTime = intent?.getLongExtra("TRIGGER_TIME", System.currentTimeMillis()) ?: System.currentTimeMillis() // 写入本地数据库 val dbHelper = NotificationDBHelper(ctx) val db = dbHelper.writableDatabase val values = ContentValues().apply { put(NotificationDBHelper.COLUMN_NOTIFICATION_ID, notificationID) put(NotificationDBHelper.COLUMN_TRIGGER_TIME, presetTriggerTime) } db.insert(NotificationDBHelper.TABLE_NAME, null, values) db.close() } } } - 创建通知时,将该接收器设为
PendingIntent的目标,通知触发时系统会发送广播触发数据库写入操作。
关键注意事项
- 数据库操作需保持轻量同步,避免在回调中执行耗时任务,防止被系统终止。
- 提前申请必要权限:iOS需通知权限;Android需通知权限,Android 12+还要申请精确闹钟权限。
- 若要存储预设触发时间(如
5:00 PM on 13th March),调度通知时可将其存入通知的userInfo(iOS)或Intent额外参数(Android),触发时直接提取使用。
内容的提问来源于stack exchange,提问作者ASAD HAMEED
相关产品推荐
相关产品推荐

