I don't see a built in way to do this either and your approach using NativeModule
is what I use as well.
However, if you call setCurrentActivity
when building your ReactInstanceManager
then you can call getCurrentActivity
from your module instead of passing it through the ReactPackage
and ReactModule
constructors.
MyReactModule.java
public class MyReactModule extends ReactContextBaseJavaModule {
public MyReactModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return getClass().getSimpleName();
}
@ReactMethod
public void finish() {
Activity activity = getCurrentActivity();
if (activity != null) {
activity.finish();
}
}
}
MyReactPackage.java
public class MyReactPackage implements ReactPackage {
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new MyReactModule(reactContext));
return modules;
}
}
ReactInstanceManager Setup
mReactInstanceManager = ReactInstanceManager.builder()
.addPackage(new MyReactPackage())
.setCurrentActivity(this)
// other settings
.build();
finish()
the React Native Activity then you can importBackAndroid
fromreact-native
and then useBackAndroid.exitApp()
.