Search code examples
androidservicereact-nativeandroid-broadcastreceivernotification-listener

Set Android BroadcastReceiver on React Native


I am building an application on React Native and I would like to use the Android Service NotificationListenerService. In order to capture data from the service, I need a Broadcast Receiver. How can I set the BroadcastReceiver up at the React Native Environment?


Solution

  • The way I did it is to emit event using getJSModule

    MyListener.java

    public class MyListener extends NotificationListenerService {
    
        @Override
        public void onNotificationPosted(StatusBarNotification sbn) {
    
            if (sbn.getNotification().tickerText == null) {
                return;
            }
    
            WritableNativeMap params = new WritableNativeMap();
            params.putString("tickerText", sbn.getNotification().tickerText.toString());
            params.putString("packageName", sbn.getPackageName());
    
            MyModule.sendEvent("notificationReceived", params);
        }
    
        @Override
        public void onNotificationRemoved(StatusBarNotification sbn) {}
    }
    

    MyModule.java

    public class MyModule extends ReactContextBaseJavaModule implements ActivityEventListener {
        private static ReactApplicationContext reactContext;
    
        public MyModule(ReactApplicationContext reactContext) {
            super(reactContext);
            this.reactContext = reactContext;
            reactContext.addActivityEventListener(this);
        }
    
        public static void sendEvent(String event, WritableNativeMap params) {
            reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(event, params);
        }
        .......
    }
    

    Check here for more details about sending events.