I\'m attempting to bridge over the Android functionality of keeping the screen on to React Native. I figured I could do this with a simple module, however I don\'t know how
For 0.28 and before, you can get activity from ReactInstanceManagerImpl
's private @Nullable Activity mCurrentActivity;
, 0.29+ 's ReactContextBaseJavaModule
using the same field.
Editted:
The issue is that getReactApplicationContext() returns the context of the Application and not the Activity. You cannot typecast an Application context to an Activity.
This is a simple workaround
Since usually, there is only one activity (Main Activity) in react-native, We can write a static function in MainActivity to return the activity
private static Activity mCurrentActivity = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCurrentActivity = this;
...
}
...
public static Activity getActivity(){
Activity activity = new Activity();
activity = mCurrentActivity;
return activity;
}
then call MainActivity.getActivity()
from the bridge modules
For custom UI component, you can get the context in the constructor, and later you can get the activity by context.getCurrentActivity()