开发者

Handling received message in running thread

I have Threads that listens to incomi开发者_如何学运维ng HTTP messages , i want to enable other developer that use my code to be able to use the messages that i received in any time. I saw in some mobile OS you can implement class and override onRecive function to receive the messages .

is this the right architecture to use in this case? if yes how could i implemented and if its not what is the best way to do it.


You can have a interface which another develoepr can implement and register with your code to be notified when a new message etc has arrived. There are any number of ways this can be achieved.

You could use the built in Observable class. or you could do something like this.

public interface Listener<T> {
    public void onEvent(T t);
}

public class Listenable<T> {
    private final List<Listener<T>> list = new CopyOnWriteArrayList<Listener<T>>();

    public void register(Listener<T> listener) {
        if (!list.contains(listener)) list.add(listener);
    }

    public void unregister(Listener<T> listener) {
        list.remove(listener);
    }

    public void onEvent(T t) {
        for (Listener<T> tListener : list) 
            tListener.onEvent(t);
    }
}

The caller could implement the Listener interface or provide an object which does. It then registers this with the Listenable. The listenable can notify all registered listeners.


Take a look at the Observer Pattern.

You can have an interface called MessageListener:

public interface MessageListener{
    void onMessage(String message);
}

Users of your library will create their own MessageListeners and will implement the onMessage method which defines what should be done when a message is received. They will also set (or register) this MessageListener with your "threads" before they are started.

Now whenever your thread gets a message, it will notify the listener(s) registered with it by calling the onMessage method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜