How to create a listener to a method in java

后端 未结 1 908
抹茶落季
抹茶落季 2021-02-06 19:16

I\'m having a really bad time to implement a listener to a method.

In my current work i have to request a method every 5 seconds in order to verify for new information

相关标签:
1条回答
  • 2021-02-06 20:02

    Ok i manage to solve my problem.

    I implemented a listener based on observer model. For that i had to implement a interface that i called XMPPmessageListener:

    public interface XMPPmessageListener {
        public void readMsg(String senderJID, String msg); 
    }
    

    than in the XmppHandler class, the class of the methods processMessage and getMessage i added methods to add and remove listeners and a LinkedList to store the listeners:

    private LinkedList<XMPPmessageListener> listeners = new LinkedList<XMPPmessageListener>();
    
    public void addMsgListener(XMPPmessageListener listener){
        listeners.add(listener);
    }
    
    public boolean removeMsgListener(XMPPmessageListener listener){
        return listeners.remove(listener);
    }       
    

    than i did some exchanges in processMessage method in order to warn the listeners:

    public void processMessage(Chat chat, Message message) {
        if (message.getType() == Message.Type.chat) {
            for(XMPPmessageListener l: listeners){
                l.readMsg(chat.getParticipant().toString(), message.getBody().toString());
            }
        }
    } 
    

    Now i can be notified at any method everytime a message is receive by creating a XMPPmessageListener and decide what to do with the message by overriding the readMsg method:

    XmppHandler xmpp = new XmppHandler(XMPPuser, XMPPpassword, XMPPaddress, XMPPdomain, XMPPport);
    
    XMPPmessageListener msglistener = new XMPPmessageListener() {
    
                    @Override
                    public void readMsg(String senderJID, String msg) {
                        String asw=xmlHandler.processMsg(msg,senderJID);
    
                    }
                };
                xmpp.addMsgListener(msglistener);
    
    0 讨论(0)
提交回复
热议问题