Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a callback handler to notify multiple listeners in Android

Tags:

java

android

I have an Android application that interfaces 3rd party hardware through a vendor-supplied library. When data from the hardware is ready to be processed, the library calls back to my application.

The 3rd party library, due to it's design, only makes one callback to the application. However, my app has a few different asynchronous tasks that it would like to do when the callback is called (for example, logging, update the UI display, call external programs). Trying to fan out the event, in a way, to different methods. So, I'm thinking about doing this in my Application class:

interface MyCallback {
    public void doSomething(ArrayList<DataClass>);
}

public class MyApp extends Application {
...
private MyCallback cb; 
public void registerCallback (MyCallback callback) {
    cb = callback;
}

public methodCalledBy3rdPartyAPIOnData (ArrayList<DataClass> data){
    cb.doSomething(ArrayList<DataClass> data);
}

which would work for a single method to call, but I'm having an issue on how to do this for a series of callbacks...and making sure they get called asynchronously. Are there any examples or best practices for doing this sort of thing in an Android application, or in Java in general?

like image 918
chromicant Avatar asked May 20 '13 14:05

chromicant


1 Answers

I would use a slightly adapted Observer Pattern (the adaptation is notifying each observer in a new thread):

Your callback handler is the subject (i.e., being observed):

public class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers(final Object data) {
        for (final Observer observer : observers) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    observer.notify(data);
                }
            }).start();
        }
    }

    public methodCalledBy3rdPartyAPIOnData (ArrayList<DataClass> data){
        notifyObservers((Object)data);
    }
}

And each of the real handlers needs to implement the following interface

public interface Observer {
    public void notify(Object data);
}

And register itself by calling subject.registerObserver(this).

like image 79
Vincent van der Weele Avatar answered Nov 14 '22 03:11

Vincent van der Weele