How to access Activity from a React Native Android module?

前端 未结 9 722
星月不相逢
星月不相逢 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: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

提交回复
热议问题