Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native + Android Activity onPause/onResume

I have js code with a next emitter:

DeviceEventEmitter.addListener('keyboardWillShow1', function(e: Event) {
  console.log(e);
});

How I can emit this event from Activity onPause/onResume?

like image 889
Simcha Avatar asked Nov 17 '15 13:11

Simcha


2 Answers

You can send event from java using RCTDeviceEventEmitter.emit method defined here: DeviceEventManagerModule.java#L27

To do it you first need to have reference to ReactApplicationContext, then call:

reactAppContext
  .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  .emit("keyboardWillShow1", null);

Instead of "null" you can send arbitrary data that will then be attached to the event you receive on JS side.

See this DeviceEventManagerModule.java#L49 as an example - this is how back button events are being send to JS.

You can then use similar pattern to dispatch events from activity onPause/onResume assuming you have reference to ReactApplicationContext

Another way would be to create your custom module, which can register for receiving lifecycle events. See how it's done in "Timing" module:

  1. "Timing" module implements LifecycleEventListener.java interface
  2. When module is initialized it registers itself to receive lifecycle through that interface Timing.java#L126
  3. You can implement onHostPause and onHostResume methods of that interface and use the snippet from the above to dispatch events from there
like image 115
kzzzf Avatar answered Sep 22 '22 09:09

kzzzf


I believe now the react-native-activity-android module accomplishes this.

like image 39
ssomnoremac Avatar answered Sep 22 '22 09:09

ssomnoremac