Simcha
Simcha

Reputation: 3400

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?

Upvotes: 5

Views: 6258

Answers (2)

ssomnoremac
ssomnoremac

Reputation: 759

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

Upvotes: 1

kzzzf
kzzzf

Reputation: 2664

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

Upvotes: 5

Related Questions