Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getCurrentActivity in ReactContextBaseJavaModule returns null

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 !

like image 679
Antoine Auffray Avatar asked Aug 01 '17 10:08

Antoine Auffray


2 Answers

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.

like image 200
Myk Willis Avatar answered Jan 01 '23 23:01

Myk Willis


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
    }
}
like image 23
Muchtarpr Avatar answered Jan 01 '23 22:01

Muchtarpr