如何实现Android原生模块向React Native的通知操作传递与处理?
sendEvent to Return Notification Action & Bridge RN Notification Handling Got it, let's break this down step by step. You need to adjust your sendEvent method to return a NotificationCompat.Action while still enabling communication between your Android native module and React Native when the notification action is tapped. Here's how to make it work:
1. Rewrite the sendEvent Method to Return NotificationCompat.Action
The original sendEvent was a void method—we'll refactor it to create a notification action that triggers an RN event when tapped. We'll use a PendingIntent linked to a broadcast receiver, which will handle sending the event to React Native behind the scenes.
// First, create a BroadcastReceiver to handle the action tap private class NotificationActionReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Extract event data passed from the notification action String eventName = intent.getStringExtra("EVENT_NAME"); String message = intent.getStringExtra("MESSAGE"); // Send the event to React Native (reusing your original event logic) WritableMap params = Arguments.createMap(); params.putString("message", message); ((ReactContext) context) .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } } // Now rewrite sendEvent to build and return a NotificationCompat.Action private NotificationCompat.Action sendEvent(ReactContext reactContext, String eventName, String message) { // Create an intent to trigger our broadcast receiver Intent intent = new Intent(reactContext, NotificationActionReceiver.class); intent.putExtra("EVENT_NAME", eventName); intent.putExtra("MESSAGE", message); // Use a unique request code to avoid overlapping pending intents int requestCode = (int) System.currentTimeMillis(); PendingIntent pendingIntent = PendingIntent.getBroadcast( reactContext, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); // Build and return the notification action return new NotificationCompat.Action.Builder( R.drawable.ic_action_send, // Replace with your action icon "Send", // Text displayed on the notification action button pendingIntent ).build(); }
2. Register the Broadcast Receiver
You need to register the NotificationActionReceiver so the system can trigger it when the action is tapped. For a React Native module, dynamic registration in your module's init method works best:
// Add this in your native module's constructor or initialization method NotificationActionReceiver actionReceiver = new NotificationActionReceiver(); reactContext.registerReceiver( actionReceiver, new IntentFilter("com.yourapp.NOTIFICATION_ACTION_TRIGGER") // Use your app's custom filter );
3. Update Your Notification Builder Code
Now you can use the updated sendEvent method directly in your notification builder—no more type mismatch errors:
NotificationCompat.Builder informativeNotification = new NotificationCompat.Builder(reactContext, "channelId") .setSmallIcon(R.drawable.avatar) .setStyle(new NotificationCompat.DecoratedCustomViewStyle()) .setContentIntent(pendingIntent) .setCustomContentView(collapseNotification) .setGroup(GROUP_KEY_WORK_EMAIL) .setGroupSummary(true) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setNumber(1) .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE) .addAction(sendEvent(reactContext, "action", "message")) // Now this works seamlessly! .setAutoCancel(true); // Don't forget to build and show the notification NotificationManagerCompat notificationManager = NotificationManagerCompat.from(reactContext); notificationManager.notify(1, informativeNotification.build());
4. Listen for the Event in React Native
Add an event listener in your RN code to handle the notification action tap and run your desired logic:
import { NativeEventEmitter, NativeModules, useEffect } from 'react-native'; // Replace with your actual native module name const { YourCustomNativeModule } = NativeModules; const notificationEventEmitter = new NativeEventEmitter(YourCustomNativeModule); // Subscribe to the notification action event useEffect(() => { const subscription = notificationEventEmitter.addListener('action', (data) => { console.log('Notification action tapped! Message:', data.message); // Add your RN logic here (e.g., navigate to a screen, show an alert) }); // Clean up the subscription when the component unmounts return () => subscription.remove(); }, []);
Quick Notes
- Replace placeholder values like
com.yourapp.NOTIFICATION_ACTION_TRIGGER,R.drawable.ic_action_send, andYourCustomNativeModulewith your app's actual values. PendingIntent.FLAG_IMMUTABLEis required for Android 12+—useFLAG_MUTABLEonly if you need to modify the intent data later (immutable is safer for most use cases).- The dynamic
requestCodeensures each notification action has a unique PendingIntent, preventing conflicts between multiple notifications.
内容的提问来源于stack exchange,提问作者Yassine Ben ghanem

