简体   繁体   English

如何拦截java中的事件

[英]How to intercept event in java

I'm working on an app in react native and I implemented a module that sends java event to js so it can be listened in react native. 我正在使用本机的应用程序,我实现了一个将java事件发送到js的模块,因此可以在本机中进行侦听。

Is there any way to listen it in another java file? 有没有办法在另一个java文件中监听它?

Here is the example event: 以下是示例事件:

            int score = 10;

            sendEvent("SCORE", score);

The module itself looks as below: 模块本身如下所示:

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

I can read it with listener in js, but have no clue how to read it in another java file. 我可以在js中用监听器读取它,但不知道如何在另一个java文件中读取它。

The best way to do this is probably to store the result and event name as a java variable, then you can easily access it from elsewhere. 执行此操作的最佳方法可能是将结果和事件名称存储为java变量,然后您可以从其他位置轻松访问它。

The first thing to do is to make a java variable that will be available from another class (public) and give it a default value to avoid any issues. 要做的第一件事是创建一个可从另一个类(公共)获得的java变量,并为其提供一个默认值以避免任何问题。

//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;
}

Now you can get the result from another Java class like below. 现在,您可以从另一个Java类获取结果,如下所示。 Just replace classWithEvent with the real name of the class that contains your sendEvent method: 只需将classWithEvent替换为包含sendEvent方法的类的真实名称:

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

Edit: This event is already doing the listening, so there is no need to listen in another java class. 编辑:此事件已经在进行侦听,因此无需在另一个java类中进行侦听。 Instead, you can simply call a method in another class, a bit like this, then whenever the sendEvent happens you can do whatever you want with it in that class: 相反,您可以简单地在另一个类中调用一个方法,就像这样,然后每当sendEvent发生时,您可以在该类中执行任何您想要的操作:

myOtherClass.doEvent(eventName, result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM