简体   繁体   中英

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 ?

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

我相信现在react-native-activity-android模块实现了这一点。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM