androidreact-nativenative-module

Android Native to React Native bridge


I've been searching on how to make a bridge between React Native and Android Native code for a while, but I still don't quite get it. I've read the documentation here , but I don't quite understand it. What I want to do is, I want to build an apps that utilize push notification, but since I need to push message to China, I can't use GCM (thanks to the great firewall), so I use another third party push SDK.

I've managed to integrate the push into my apps (resulting a console.log() message whenever I push something), the next step is I want to re-route it to certain page

Any help will be appreciated :)


Solution

  • Note: If you are using common push notification (i.e. GCM and APNS), use this instead. Since I need to use another third party push service, I need to find a way myself to bridge the SDK (which is native) to React Native.

    So after several hours tinkering with this problem, I found a solution for my problem. This solution divided into 2 parts:

    1. emitter, this will emits an event whenever the server send a push.
    2. listener, this will listen to the event that you emits before.

    emitter

    This happens on the native side (Android in my case)

    For this part I learnt it from how this library did using GCM. And found a tutorial here on the RN documentation.

    Basically after you receive your push on SomeBroadCastReceiver onReceive() function, you can pass the bundle as params in this function

    reactContext
      .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
      //this eventName is a key so you need to remember it, because you need to call it on the listener
      .emit(eventName, params);
    

    listener

    The listener will be built on the RN side. this documentation helps me. I missed this documentation before, because it only appear in the RN iOS docs only.

    import { NativeEventEmitter, NativeModules } from 'react-native';
    //import your already created package name here
    const { YourCustomPackageName} = NativeModules;
    

    then in ComponentWillMount()

    const yourCustomPackageEmitter = new NativeEventEmitter(YourCustomPackageName);
    pushListenerEmitter.addListener(eventName, this.handlePush, this);
    

    then you just need to create handlePush function and get the params there

    handlePush = (event) => {
        console.log('event triggered..');
        console.log(event);
    }