如何拦截 java 中的事件

How to intercept event in java

我正在使用 React Native 开发一个应用程序,我实现了一个模块,该模块将 java 事件发送到 js,以便可以在 React Native 中收听。

有没有办法在另一个 java 文件中收听它?

示例事件如下:

            int score = 10;

            sendEvent("SCORE", score);

模块本身如下所示:

// Called to emit events to event listeners in JS
private void sendEvent(String eventName, int result) {
    getReactApplicationContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, result);

我可以在 js 中使用 listener 读取它,但不知道如何在另一个 java 文件中读取它。

执行此操作的最佳方法可能是将结果和事件名称存储为 java 变量,然后您可以从其他地方轻松访问它。

首先要做的是创建一个 java 变量,该变量可从另一个 class (public) 获得,并为其提供默认值以避免任何问题。

//Create Java variables
public static int myValueResult = 0;
public static string myValueName = "";

// Called to emit events to event listeners in JS
private void sendEvent(String eventName, int result) {
getReactApplicationContext()
        //JS Method
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit(eventName, result);

        //Add an extra line that saves the result and eventName to the Java variables we made 
        myValueResult = result;
        myValueName = eventName;
}

现在您可以从另一个 Java class 获得结果,如下所示。只需将 classWithEvent 替换为包含您的 sendEvent 方法的 class 的真实名称:

int resultFromOtherClass_result = classWithEvent.myValueResult;
string resultFromOtherClass_name = classWithEvent.myValueName;

编辑:这个事件已经在监听了,所以没有必要在另一个javaclass中监听。相反,您可以简单地调用另一个 class 中的方法,有点像这样,然后每当 sendEvent 发生时,您可以在 class:

中用它做任何你想做的事
myOtherClass.doEvent(eventName, result);