Antoine Auffray
Antoine Auffray

Reputation: 1293

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 !

Upvotes: 14

Views: 6127

Answers (2)

Muchtarpr
Muchtarpr

Reputation: 97

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
    }
}

Upvotes: 1

Myk Willis
Myk Willis

Reputation: 12879

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.

Upvotes: 6

Related Questions