ReactNative与java交互

在ReactNative中与Android进行交互

第一实现ReactContextBaseJavaModule接口,

在ReactContextBaseJavaModule中与React交互的方法需要@ReactMethod注解:如下

    public class ToastExampleMoudle extends ReactContextBaseJavaModule {
        private static final String MESSAGE = "MESSAGE";
        public ToastExampleMoudle(ReactApplicationContext reactContext) {
            super(reactContext);
        }
        @Nullable
        @Override
        public Map getConstants() {
            //让js那边能够使用这些常量
            Map constants = new HashMap<>();
            return constants;
        }

        @ReactMethod
        public void show(int duration){
            Toast.makeText(getReactApplicationContext(), "dongnao:" + duration, Toast.LENGTH_SHORT).show();
        }
        @ReactMethod
        public void testAndroidCallBack(String msg, Callback callback) {
            Toast.makeText(getReactApplicationContext(),msg,Toast.LENGTH_LONG).show();
            callback.invoke("david");
        }
        @ReactMethod
        public void textAndroidPromiseMethod(String msg, Promise promise){
            Toast.makeText(getReactApplicationContext(),msg,Toast.LENGTH_SHORT).show();
            String result = "david";
            promise.resolve(result);
        }
    @ReactMethod
        public void onScaning() {
            WritableMap params = Arguments.createMap();
            params.putString("key","mydata");
            getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                    .emit("EventName", params);
        }
        @Override
        public String getName() {
            return "ToastForAndroid";//名称
        }

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

上面代码中我使用四种方式与react交互
1、show方法直接获得react数据
2、testAndroidCallBack方法获得react数据之后需要放回数据给react这里采用Callback接口回调
3、textAndroidPromiseMethod方法是Promise返回给react数据
4、onScaning方法是react调用Java

第二步、实现ReactPackage接口

在实现ReactPackage接口之后 需要在实现的接口中需要添加Module模块
如下:

    /注册模块
    public class ExampleReactNativePackage implements ReactPackage {
    //完成注入需要被js调用java方法
        @Override
        public List createNativeModules(ReactApplicationContext reactContext) {
            List modules = new ArrayList<>();
            modules.add(new ToastExampleMoudle(reactContext));
            return modules;
        }

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

第三步 需要在MainApplication中重写getPackage方法将注册ExampleReactNativePackage添加进去
如下

      private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List getPackages() {
          return Arrays.asList(
              new MainReactPackage(),
                  new ExampleReactNativePackage()//添加进去
          );
        }
        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };

第四、js调用原生的
需要导入import {NativeModules} from 'react-native';
如下

    import React, {Component} from 'react';
    import {Platform, StyleSheet,ToastAndroid, DeviceEventEmitter,Text, TouchableOpacity,View,NativeModules} from 'react-native';

    export default class App extends Component {
      constructor(props){
        super(props);
        this.state= {
          text:"river",
          text2: "默认",
        }

        }

        componentDidMount(): void {
          //观察者对象     监听java  调用js
          DeviceEventEmitter.addListener("EventName",function (msg) {
            let rest = NativeModules.ToastForAndroid.MESSAGE;
            ToastAndroid.show("DeviceEventEmitter收到消息:" + "\n" + rest, ToastAndroid.SHORT)
          })

        }

      _onPressButton(){
        NativeModules.ToastForAndroid.show(1000);//表示传递数据给java
      }

      _onPressButton2(){
      //表示表示传递数据给java之后, Java返回数据给js
        NativeModules.ToastForAndroid.testAndroidCallBack("hello David",(result)=>{
            this.setState({
              text: result
            })
        });
      }

      _onPressButton3(){
        //表示表示传递数据给java之后, Java通过Promise返回数据给js
        NativeModules.ToastForAndroid.textAndroidPromiseMethod("hello David").then((result)=>{
          this.setState({
            text2: result
          })
        })
      }
      _onPressButton4(){
      //java传递传递数据给js
        NativeModules.ToastForAndroid.onScaning();
      }

你可能感兴趣的:(ReactNative与java交互)