React Native Android如何获取已调度的本地通知?
解决React Native中Android端获取已调度本地通知的问题
嘿,这个问题我太有共鸣了!我之前在用react-native-push-notification做跨平台本地通知时,也踩过Android端没法直接获取已调度通知的坑——毕竟这个库在iOS端封装了PushNotificationIOS.getScheduledLocalNotifications,但Android端确实没有对应的内置方法。不过有两种靠谱的解决方案:
方案一:自行维护已调度通知的本地记录(推荐)
这是最通用、最省心的跨平台方案,原理很简单:每次调用localNotificationSchedule调度通知时,把通知的ID和配置信息存在本地存储(比如AsyncStorage、Realm或者MMKV)里,需要获取时直接从存储中读取就行。同时记得在通知触发、被取消时更新这个列表,保证数据一致性。
代码示例:
import PushNotification from 'react-native-push-notification'; import AsyncStorage from '@react-native-async-storage/async-storage'; // 调度通知并保存记录 const scheduleNotification = async (notificationConfig) => { // 生成唯一通知ID(用时间戳或UUID都可以) const notificationId = Date.now().toString(); const scheduledNote = { id: notificationId, ...notificationConfig }; // 执行调度 PushNotification.localNotificationSchedule({ ...notificationConfig, id: notificationId, // 你的其他配置:date、title、message等 }); // 保存到本地存储 try { const existingNotes = await AsyncStorage.getItem('scheduledNotifications'); const notesArray = existingNotes ? JSON.parse(existingNotes) : []; notesArray.push(scheduledNote); await AsyncStorage.setItem('scheduledNotifications', JSON.stringify(notesArray)); } catch (err) { console.error('保存调度通知记录失败:', err); } }; // 获取所有已调度通知 const getScheduledNotifications = async () => { try { const existingNotes = await AsyncStorage.getItem('scheduledNotifications'); return existingNotes ? JSON.parse(existingNotes) : []; } catch (err) { console.error('获取调度通知记录失败:', err); return []; } }; // 取消通知并更新记录 const cancelNotification = async (notificationId) => { PushNotification.cancelLocalNotifications({ id: notificationId }); try { const existingNotes = await AsyncStorage.getItem('scheduledNotifications'); if (existingNotes) { const updatedNotes = JSON.parse(existingNotes).filter(note => note.id !== notificationId); await AsyncStorage.setItem('scheduledNotifications', JSON.stringify(updatedNotes)); } } catch (err) { console.error('移除取消的通知记录失败:', err); } };
方案二:编写Android原生模块扩展
如果你不想依赖本地存储,想直接从Android系统层面获取已调度通知,就需要自定义原生模块。不过要注意:Android系统并没有提供直接获取所有已调度通知的API,不同版本的系统限制也不一样,维护成本会高一些。
大致步骤:
- 创建Android原生模块,通过
AlarmManager或NotificationManager尝试获取已调度的闹钟/通知(注:AlarmManager.getNextAlarmClock()只能获取下一个即将触发的闹钟,无法获取全部) - 将原生模块注册到React Native项目中
- 在JS端调用原生模块的方法获取数据
原生模块代码示例(简化版):
// NotificationModule.java package com.yourAppPackage; import android.app.AlarmManager; import android.content.Context; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.WritableNativeArray; import com.facebook.react.bridge.WritableNativeMap; public class NotificationModule extends ReactContextBaseJavaModule { private static final String MODULE_NAME = "NotificationModule"; private final ReactApplicationContext reactContext; public NotificationModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return MODULE_NAME; } @ReactMethod public void getScheduledLocalNotifications(com.facebook.react.bridge.Callback successCallback) { AlarmManager alarmManager = (AlarmManager) reactContext.getSystemService(Context.ALARM_SERVICE); WritableArray notifications = new WritableNativeArray(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { AlarmManager.AlarmClockInfo nextAlarm = alarmManager.getNextAlarmClock(); if (nextAlarm != null) { WritableMap noteMap = new WritableNativeMap(); noteMap.putLong("triggerTime", nextAlarm.getTriggerTime()); notifications.pushMap(noteMap); } } successCallback.invoke(notifications); } }
JS端调用:
import { NativeModules } from 'react-native'; const { NotificationModule } = NativeModules; // 获取已调度通知 NotificationModule.getScheduledLocalNotifications((notifications) => { console.log('Android已调度通知:', notifications); });
总的来说,方案一的实用性和跨平台兼容性更强,除非你有特殊需求,否则优先考虑自行维护本地记录。
内容的提问来源于stack exchange,提问作者A.Matt
相关产品推荐
相关产品推荐

