簡體   English   中英

如何攔截java中的事件

[英]How to intercept event in java

我正在使用本機的應用程序,我實現了一個將java事件發送到js的模塊,因此可以在本機中進行偵聽。

有沒有辦法在另一個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中用監聽器讀取它,但不知道如何在另一個java文件中讀取它。

執行此操作的最佳方法可能是將結果和事件名稱存儲為java變量,然后您可以從其他位置輕松訪問它。

要做的第一件事是創建一個可從另一個類(公共)獲得的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;
}

現在,您可以從另一個Java類獲取結果,如下所示。 只需將classWithEvent替換為包含sendEvent方法的類的真實名稱:

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

編輯:此事件已經在進行偵聽,因此無需在另一個java類中進行偵聽。 相反,您可以簡單地在另一個類中調用一個方法,就像這樣,然后每當sendEvent發生時,您可以在該類中執行任何您想要的操作:

myOtherClass.doEvent(eventName, result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM