Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 28463

How to make sure JS Modules are loaded before sending message from ReactActivity via JS bridge?

$
0
0

In my react app the MainActivity(subclass of ReactActivity) is launched from the subclass of BroadcastReceiver. From the MainActivity::onCreate method a message to JS Module is emitted through JS bridge which gets lost. From the logs it looks like the JS Module gets mounted after the message is sent from MainActivity::onCreate() method.

ExampleReceiver.java

public class ExampleReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, ANService.class);
        service.putExtras(intent);
    service.setClassName("com.example", "com.example.MainActivity");
        service.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(service);
    }
}

MainActivity.java

public class MainActivity extends ReactActivity {
    ...
    ...
  @Override
  protected void onCreate (Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Log.d(TAG, "onCreate -> MainActivity -> ReactActivity");
      try {
      JSONObject data = BundleJSONConverter.convertToJSON(getIntent().getExtras());
      Log.d(TAG, data.toString());
          getReactInstanceManager().getCurrentReactContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("onExampleMessage", data.toString());
      } catch (Exception e) {
          System.err.println("Exception when handling notification openned. " + e);
      }
  }
}

ExampleJSComponent.js

export default class ExampleJSComponent extends Component
{
    componentDidMount() {
    console.log('ExampleJSComponent componentDidMount');

    DeviceEventEmitter.addListener('onExampleMessage', async function(e) {
        const obj = JSON.parse(e);
        console.log(obj);
    });
    }
}

Adb logcat Logs:
...
...
D MainActivity: onCreate -> MainActivity -> ReactActivity
...
...
I ReactNativeJS: in index.js
I ReactNativeJS: ExampleJSComponent componentDidMount


The following line does not ensure the JS components are mounted.

getReactInstanceManager().getCurrentReactContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)

How to make sure the JS component is mounted before sending message from the MainActivity::onCreate method ?


Viewing all articles
Browse latest Browse all 28463

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>