我试图跨越将功能保持在React Native的Android功能.我想我可以用一个简单的模块来做,但是我不知道如何从所述模块访问当前的Android Activity.
我需要Activity参考,所以我可以调用.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);在上面
我试图通过这样的((Activity)getReactApplicationContext().getBaseContext())通过转换来获取活动,但是这会抛出一个“不能被转换为Android.app.Activity”错误
CustomReactPackage.java:
public class CustomReactPackage implements ReactPackage { private Activity mActivity = null; public CustomReactPackage(Activity activity) { mActivity = activity; } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); // Add native modules here return modules; } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> modules = new ArrayList<>(); // Add native UI components here modules.add(new LSPlayerManager(mActivity)); return modules; } }
LSPlayerManager是我的本地UI组件.我定义一个构造函数,以便我可以传入活动:
public LSPlayerManager(Activity activity) { mActivity = activity; }
最后在定义了ReactInstanceManager的MainActivity.java中,我们可以将该活动传递给我们的自定义React包:
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();
REACT NATIVE更新为0.29.0
这不再是在本机模块中访问活动的方式.有关迁移说明,请参见https://github.com/facebook/react-native/releases/tag/v0.29.0