Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 759
user3348949 Avatar asked Mar 01 '17 22:03

user3348949


1 Answers

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.

like image 50
vinayr Avatar answered Oct 31 '22 02:10

vinayr