Mobile/React-Native

React-native 네이티브(Android)와 통신하기(eventEmitter)

WonYoungJae 2023. 2. 23. 12:29

블루투스 스캔 기능 구현하다가 npm에 있는 라이브러리들이 별로라 직접 구현하기로 했다.

 

스캔 결과를 React-native 쪽으로 던져줘야해서 EventEmitter 사용하여 구현하던 중에 React-native로 데이터를 던지면 에러가 뿅뿅 발생 했다.

 

NativeModule에서 Service(백그라운드에서도 동작해야 해서)를 실행하여 Service에서 EventEmitter 통해 React-native로 스캔 결과를 던져주는 순서로 구현을 해놨는데 Service에서 생성한 ReactContext를 잘못 생성해줘서 생긴 에러였다.

 

기존 코드

// Activity Context로 생성하면 안됨 (NullPointerException)
ReactContext reactContext = new ReactContext(this);

// ReactContext가 initialize되지 않아 안됨 (IllegalStateException)
ReactContext reactContext = new ReactContext(this.getApplication());

수정 코드

// React 인스턴스를 가져와 해당 인스턴스에서 ReactContext를 가져와야 한다.
ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager();
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();

// 이런식으로 사용하면 된다.
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("이벤트 이름", "보낼 데이터");

앱 개발자가 아니다 보니 하나하나 찾아가면서 개발하기가 너무 힘들다. 하하하하

NativeModule은 iOS가 더 나은거 같다. 뭔가 더 간단한 느낌.

 

마지막으로 React-native에서 사용법이다.

import {NativeModules, NativeEventEmitter} from 'react-native';

const {모듈이름} = NativeModules;

const emitter = new NativeEventEmitter(모듈이름);

emitter.addListener(
    '이벤트 이름',
    () => {
        // ...코드 작성
    }
)
728x90