2019-04-10Android跟ReactNative通信的几种方式

方式一:原生主动向RN发送数据
第一步:在MainApplication中 添加Package 它实现了ReactApplication接口代码如下:

 private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

        @Override
        protected String getJSBundleFile() {
            return CodePush.getJSBundleFile();
        }


        @Override
        protected List getPackages() {
            return Arrays.asList(
                    new MainReactPackage(),
                    updateDownloadPackage, //这里以updateDownloadPackage为例子
                    new RNGestureHandlerPackage(),
                    new CodePush(getResources().getString(R.string.reactNativeCodePush_androidDeploymentKey), getApplicationContext(), BuildConfig.DEBUG)

            );
        }

        @Override
        protected String getJSMainModuleName() {
            return "index";
        }

        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }
    };

接下来看看Packager的代码例子

public class UpdateDownloadPackage implements ReactPackage {


    @Override
    public List createNativeModules(ReactApplicationContext reactContext) {
        List modules=new ArrayList<>();
        modules.add(new UpdateDownloadModule(reactContext));
        return modules;
    }

    @Override
    public List createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

接下来的重点还是在Module中,代码如下:

public class UpdateDownloadModule extends ReactContextBaseJavaModule {

    public static final String MODULE_NAME="updateDownloadModule";
    public static final String EVENT_NAME = "nativeCallRn";
    public ReactApplicationContext context ;

    public UpdateDownloadModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.context = reactContext;
    }

    @Override
    public String getName() {
        return MODULE_NAME;
    }
  
   //新版RN多了一个initalize方法 ,如果是老版本没有这个方法可以直接在MainActivity中实现
    @Override
    public void initialize() {
        Log.i("gdchent","module_initialize");
        nativeCallRn("需要的数据"); //这里可以传json对象
    }

    @Override
    public boolean canOverrideExistingModule() {
        return false;
    }

    @Override
    public void onCatalystInstanceDestroy() {

    }

    /**
     * Native调用RN
     * @param msg
     */
    public void nativeCallRn(String msg) {
        Log.i("gdchent","apkUrl"+msg);
        context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(EVENT_NAME,msg);

    }
}

RN端接收数据:

import { DeviceEventEmitter } from 'react-native';
  /**
    * 接收原生调用
    */
   componentDidMount() {

       DeviceEventEmitter.addListener('nativeCallRn',(msg)=>{
            title = "React Native界面,收到数据:" + global.patchImgNames;
            ToastAndroid.show("发送成功", ToastAndroid.SHORT);
       })
   }

方式2:调用原生代码跳转到原生界面

...详情参见GitHub传送门
https://github.com/gdchent/NavigationApp

你可能感兴趣的:(2019-04-10Android跟ReactNative通信的几种方式)