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?
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With