I'm coding a native Android module with React Native 0.46 and I have trouble getting the current activity instance from the module.
I have a class extending ReactContextBaseJavaModule, which contains a built-in getCurrentActivity() method. However, each time I call this method, I get a null.
I think it's because I'm calling this in my module constructor, which is executed at the start of the Android application, maybe before an Activity is instantiated ?
If you guys know a clean way to access the current Activity instance from within the module (without having to store an Activity instance at some point and passing it around, if possible), I'll be glad !
According to these posts on the react-native GitHub page, it is by design that you cannot access the current activity in the constructor of a native module. The modules may be used across Activities, and may be created before an associated Activity has resumed.
The expectation is that you can use getCurrentActivity
when needed during operations, for example from any @ReactMethod
in the module.
same as Myk Willis
answer, getCurrentActivity can be accessed inside @ReactMethod like this example:
public class ExampleModule extends ReactContextBaseJavaModule {
Activity activity;
@ReactMethod(isBlockingSynchronousMethod = true)
public void MinimizeExample(String params) {
activity = getCurrentActivity(); // get current activity
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With