定义OpenNativeModule 类,实现sendEventToRn静态方法。
public class OpenNativeModule extends ReactContextBaseJavaModule { private ReactContext mReactContext; private static ReactContext myContext; public OpenNativeModule(ReactApplicationContext context) { super(context); this.mReactContext = context; this.myContext = context; } @Override public String getName() { return "OpenNativeModule"; } public static void sendEventToRn(String eventName, @Nullable WritableMap paramss) { myContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, paramss); } @ReactMethod // 提供给RN调用的方法 public void openNativeVC() { Intent intent = new Intent(); intent.setClass(mReactContext, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mReactContext.startActivity(intent); }}
Android 原生方法中调用
// WritableMap 对应 JS 中的 ObjectWritableMap event = Arguments.createMap(); //传递的参数event.putString("userRes",content);OpenNativeModule.sendEventToRn("LoginSuccess", event);
RN监听
componentDidMount() { this.emitListener = DeviceEventEmitter.addListener('LoginSuccess', (e) => { // todo alert(e.userRes); });}