gpt4 book ai didi

java - React Native(Android 原生模块): Get access to ReactContext in another Class?

转载 作者:行者123 更新时间:2023-12-01 04:58:16 25 4
gpt4 key购买 nike

我想在 MyCustomModuleClass 中调用一个方法,从另一个类扩展 ReactContextBaseJavaModule

MyCustomModule.java


public class MyCustomModule extends ReactContextBaseJavaModule {

private ReactContext mReactContext;

public MyCustomModule(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
}

@Override
public String getName() {
return "CustomModule";
}


private void sendEvent(String eventName, Object params) {
mReactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
}

我正在尝试这个..

OtherClass.java


public class OtherClass extends AnotherClass {

@Override
protected void eventOccurred(Context context) {
MyCustomModule RNC = new MyCustomModule(?);//-> Can't call without ReactContext
RNC.sendEvent("CustomEvent", ObjectData);
}
}

不好意思,我对java一窍不通,谁能帮帮我?

有什么办法可以在 OtherClass 中获取 ReactContext 吗?

最佳答案

这是我在 FirebaseMessagingService 中的做法扩展类。

public class MyPushListener extends FirebaseMessagingService {

@Override
public void onMessageReceived(JSONObject message, JSONObject content){

MainApplication application = (MainApplication) this.getApplication();

ReactNativeHost reactNativeHost = application.getReactNativeHost();
ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();

if (reactContext != null) {
WritableNativeArray params = new WritableNativeArray();
params.pushString(message.toString());
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("EVENT_HAS_TRIGGERED", params);
}
}
}

Source

关于java - React Native(Android 原生模块): Get access to ReactContext in another Class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35278646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com