如何在react-native-firebase/messaging中打开应用后清除通知角标计数
应用内更新通知角标计数的解决方案
@react-native-firebase/messaging 模块本身没有提供直接操作通知角标的API,但可以通过以下几种方式实现需求:
一、使用 @react-native-firebase/notifications 模块
rnfirebase生态中的notifications模块支持角标管理,步骤如下:
- 安装模块(未安装的话):
npm install @react-native-firebase/notifications # 或 yarn add @react-native-firebase/notifications
- 在通知打开监听器中重置角标:
修改你的现有代码,添加角标重置逻辑:
import messaging from '@react-native-firebase/messaging'; import notifications from '@react-native-firebase/notifications'; messaging().onNotificationOpenedApp(async (remoteMessage) => { console.log(remoteMessage); // 将角标计数设为0 await notifications().setBadgeCount(0); });
二、平台适配说明
- iOS:
setBadgeCount方法可直接生效,但需确保App已获取通知权限中的角标权限(用户授权时需包含该权限)。 - Android:角标显示依赖手机厂商,主流厂商(小米、华为、三星等)大多兼容
setBadgeCount方法;部分厂商可能需要在AndroidManifest.xml中额外配置,或调用厂商特定SDK,若遇到兼容性问题可采用原生桥接方案。
三、原生桥接替代方案(无需额外依赖)
如果不想集成notifications模块,可通过React Native的原生桥接直接调用平台API:
iOS端(Objective-C)
在AppDelegate.m中添加原生方法:
#import <UserNotifications/UserNotifications.h> RCT_EXPORT_METHOD(setBadgeCount:(NSInteger)count) { [UNUserNotificationCenter.currentNotificationCenter setBadgeCount:count withCompletionHandler:nil]; }
Android端(Kotlin)
创建自定义Native模块:
class BadgeModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName() = "BadgeModule" @ReactMethod fun setBadgeCount(count: Int) { val notificationManager = reactContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // 适配不同厂商,示例为小米的实现 try { val method = notificationManager.javaClass.getMethod("setNotificationBadgeNum", Int::class.java) method.invoke(notificationManager, count) } catch (e: Exception) { // 其他厂商可添加对应逻辑,或忽略异常 } } }
然后在React Native代码中调用:
import { NativeModules } from 'react-native'; const { BadgeModule } = NativeModules; messaging().onNotificationOpenedApp(async (remoteMessage) => { console.log(remoteMessage); BadgeModule.setBadgeCount(0); });
内容的提问来源于stack exchange,提问作者Lahfir
相关产品推荐
相关产品推荐

