Skip to content Skip to sidebar Skip to footer

Android Callback Listener - Send Value From Pojo In Sdk To An Application's Activity

I have a java class buried deep in an SDK that performs an action and returns a boolean. It has no knowledge of the application's main activity, but I need the main activity to re

Solution 1:

I'd suggest using a message bus or observable/observer pattern.

Square has Otto a nice little open-source library that implements a message bus.

Observer pattern is well described at wikipedia for example.

Either way what you will have to do is essentially start listening to either your POJO if you make it Observable, or subscribe for bus events in onResume() (or onStart()) and stop listening in onPause() in your activity.

BUS

I like bus more because of it's loose coupling and the fact that you can send any arbitrary POJOs to the bus and only listen to one specific type for example.

so you post a message this:

bus.post(newSomethingICareAbout("I really really do"));

and elsewhere in your codebase (in your case in the activity):

@Subscribe
public void onSomethingIcareAbout(SomethingICareAbout thingsAndStuff) {
    // TODO: React to the event somehow. Use what you received.
}

@Subscribe
public void onSomethingElseIcareAbout(SomethingElseICareAbout otherThings) {
    // TODO: React to the event somehow. Use what you received.
}

The above is intentionally simplified, you still need to create the bus and subscribe to it, but you will find that in the docs :P Also it uses annotations and is really lightweight (codewise).

Observer / Observable

Observer/Observable on the other had is part of Java, so it's built in. But it is tightly coupled, your activity will have to implement Observer, your POJO will implement Observable and you willl have to implement update() method in your Activity, this one will get all the updates no matter what you send by the Observable.

I hope this makes sense a bit :)

Post a Comment for "Android Callback Listener - Send Value From Pojo In Sdk To An Application's Activity"