How to access Activity from a React Native Android module?

前端 未结 9 617
星月不相逢
星月不相逢 2020-12-04 21:53

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

相关标签:
9条回答
  • 2020-12-04 22:23

    For 0.28 and before, you can get activity from ReactInstanceManagerImpl 's private @Nullable Activity mCurrentActivity;, 0.29+ 's ReactContextBaseJavaModule using the same field.

    0 讨论(0)
  • 2020-12-04 22:25

    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

    0 讨论(0)
  • 2020-12-04 22:26

    For custom UI component, you can get the context in the constructor, and later you can get the activity by context.getCurrentActivity()

    0 讨论(0)
提交回复
热议问题