React Native中如何在推送通知添加接受/拒绝按钮?
React Native 推送通知添加接受/拒绝按钮实现方案
iOS 端实现
iOS 需通过**通知类别(UNNotificationCategory)**定义按钮动作,步骤如下:
注册通知类别
以@react-native-firebase/messaging为例,在 App 启动时注册包含接受、拒绝动作的类别:import messaging from '@react-native-firebase/messaging'; import { Platform } from 'react-native'; async function setupNotificationCategories() { if (Platform.OS !== 'ios') return; // 定义接受动作 const acceptAction = messaging.Action({ identifier: 'ACCEPT', title: '接受', options: [messaging.ActionOption.Foreground], // 点击后唤起App前台 }); // 定义拒绝动作 const rejectAction = messaging.Action({ identifier: 'REJECT', title: '拒绝', options: [], // 点击后不唤起App }); // 创建并注册类别 const requestCategory = messaging.Category('REQUEST_CATEGORY', [acceptAction, rejectAction], { options: [messaging.CategoryOption.CustomDismissAction], }); await messaging.setNotificationCategories([requestCategory]); } // 在App初始化时调用 setupNotificationCategories();发送通知时关联类别
后端推送 APNs 时,需在 payload 中指定category: "REQUEST_CATEGORY";本地通知则直接设置 category:messaging().localNotification({ title: '待处理请求', body: '是否接受该协作请求?', categoryId: 'REQUEST_CATEGORY', });监听按钮点击事件
在消息回调中根据动作标识符处理逻辑:messaging().onNotificationOpenedApp(remoteMessage => { const action = remoteMessage.notification?.action; if (action === 'ACCEPT') { // 执行接受逻辑:如更新状态、发起API请求 console.log('用户接受了请求'); } else if (action === 'REJECT') { // 执行拒绝逻辑 console.log('用户拒绝了请求'); } }); // 处理App未启动时的按钮点击 messaging().getInitialNotification().then(remoteMessage => { if (remoteMessage?.notification?.action) { const action = remoteMessage.notification.action; // 同上处理逻辑 } });
Android 端实现
Android 通过**通知通道(Notification Channel)**配置按钮,以 react-native-push-notification 为例:
创建带动作的通知通道
import PushNotification from 'react-native-push-notification'; PushNotification.createChannel( { channelId: 'request-channel', channelName: '请求通知通道', channelDescription: '用于展示带操作按钮的请求通知', importance: 4, vibrate: true, }, () => {} );发送带按钮的通知
直接在通知配置中指定actions字段:PushNotification.localNotification({ channelId: 'request-channel', title: '待处理请求', message: '是否接受该协作请求?', actions: ['接受', '拒绝'], // 按钮文本 invokeApp: false, // 点击按钮不直接唤起App(可选) });监听按钮点击事件
在configure回调中处理动作:PushNotification.configure({ onNotification: notification => { if (notification.action === '接受') { // 执行接受逻辑 console.log('用户接受了请求'); } else if (notification.action === '拒绝') { // 执行拒绝逻辑 console.log('用户拒绝了请求'); } // 必须调用finish结束通知处理 notification.finish(); }, // 其他配置项... });
注意事项
- iOS 需确保 APNs 推送 payload 包含
category字段,否则按钮不显示; - Android 8.0+ 必须使用通知通道,否则通知无法展示;
- 后台状态下,需确保 App 能接收通知回调(iOS 需开启后台通知权限,Android 需配置正确的广播接收器)。
内容的提问来源于stack exchange,提问作者Sandy
相关产品推荐
相关产品推荐

