8

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?

user3348949
  • 304
  • 3
  • 4
  • 15

1 Answers1

16

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.

vinayr
  • 11,026
  • 3
  • 46
  • 42
  • Did it work? It seems I can't instantiate an WritableMap object. – user3348949 Mar 04 '17 at 12:36
  • It's actually `WritableNativeMap`. Updated my answer. – vinayr Mar 04 '17 at 14:41
  • i'm pretty new to react native so I don't fully understand eventListeners. Apparently, on the module, the compiler can't find `this.reactContext`. Is this part correct? – user3348949 Mar 04 '17 at 14:56
  • Yes it's correct. Check out my module for a complete example https://github.com/nerdyfactory/things-notification – vinayr Mar 04 '17 at 15:28
  • Thank you very much! You really helped a lot!!! You're the best! BTW, very elegant solution. – user3348949 Mar 04 '17 at 15:47
  • This is not a great idea because holding context in a static variable can cause memory leaks. See https://android-developers.googleblog.com/2009/01/avoiding-memory-leaks.html – davkutalek Mar 26 '19 at 20:00