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 to get access to the current Android Activity from said module.
I need the Activity reference so I can call .getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
on it
I tried to get the activity via casting like so ((Activity)getReactApplicationContext().getBaseContext())
, but this throws a "cannot be cast to Android.app.Activity" error
I guess
getCurrentActivity()
method of ReactContextBaseJavaModule might be used like the following code which has been copied fromReact-Native
original code;I needed to modify an outdated module (react-android-360-video) and found this helpful...
In
android/app/src/main/java/com/webcdpmobiledemo/MainApplication.java
, I used the new format for adding a package:And
android/app/src/main/java/com/webcdpmobiledemo/MainActivity.java
is essentially empty:Then, I modified the VrVideoViewPackage file, which needs to pass the
reactContext
to theVrVideoViewManager
it calls:And finally, in the
VrVideoViewManager
the activity can be accessed like so: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
then call
MainActivity.getActivity()
from the bridge modulesCustomReactPackage.java
:LSPlayerManager
is my native UI component. I define a constructor so that I can pass in the activity:And finally in
MainActivity.java
where theReactInstanceManager
is defined, we can pass the activity to our custom React package:UPDATE FOR REACT NATIVE 0.29.0
This is no longer how you access activity in a native module. See https://github.com/facebook/react-native/releases/tag/v0.29.0 for migration instructions
How do you pass the activity to a package from ReactApplication::getPackages() ?
I do not understand. I cannot find any clear examples
Answer: You do NOT pass Activity from MainApplication to the package.
You call getCurrentActivity() from within your ReactContextBaseJavaModule
For 0.28 and before, you can get activity from
ReactInstanceManagerImpl
'sprivate @Nullable Activity mCurrentActivity;
, 0.29+ 'sReactContextBaseJavaModule
using the same field.