How to access Activity from a React Native Android module?

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

    CustomReactPackage.java:

    public class CustomReactPackage implements ReactPackage {
    
        private Activity mActivity = null;
    
        public CustomReactPackage(Activity activity) {
            mActivity = activity;
        }
    
        @Override
        public List createNativeModules(ReactApplicationContext reactContext) {
            List modules = new ArrayList<>();
            // Add native modules here
            return modules;
        }
    
        public List> createJSModules() {
            return Collections.emptyList();
        }
    
        public List createViewManagers(ReactApplicationContext reactContext) {
            List modules = new ArrayList<>();
            // Add native UI components here
            modules.add(new LSPlayerManager(mActivity));
            return modules;
        }
    }
    

    LSPlayerManager is my native UI component. I define a constructor so that I can pass in the activity:

    public LSPlayerManager(Activity activity) {
        mActivity = activity;
    }
    

    And finally in MainActivity.java where the ReactInstanceManager is defined, we can pass the activity to our custom React package:

    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("index.android.bundle")
            .setJSMainModuleName("src/index.android")
            .addPackage(new MainReactPackage())
            .addPackage(new CustomReactPackage(this)) // <--- LIKE THIS!
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();
    

    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

提交回复
热议问题