Android callback listener - send value from pojo to SDK to application activity

I have a java class deeply embedded in the SDK that takes an action and returns a boolean. It doesn't know the main activity of the application , but I need the main activity to get this boolean.

I've seen a lot of questions regarding callbacks, broadcasts and listeners, but they all seem to be aware of their activity. My pojo has an ActivityContext, but I don't know how to return the value to the main activity of the application.

I am already using AsyncTask in my pojo and I am trying to figure out how to send a boolean in the onPostExecute method in such a way that the main action of the application can receive it.

Does anyone know how to do this?

+3


source to share


1 answer


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

Otto Square is a nice open source library that implements a message bus.

The observer pattern is well documented in wikipedia for example.

In any case, you will need to start listening to your POJO if you make it observable, or subscribe to bus events in onResume()

(or onStart()

) and stop listening in onPause()

in your activity.

BUS

I like the bus more because of its free communication and the fact that you can send any arbitrary POJO to the bus and only listen to one specific type, for example.

to post a message:



bus.post(new SomethingICareAbout("I really really do"));

      

and elsewhere in your codebase (in your case, in action):

@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 oversimplified, you still need to create a bus and subscribe to it, but you will find that in the docs: P Also it uses annotations and is really lightweight (by code).

Observer / Observed

Observer / Observable on the other hand is part of Java, so it's built in. But it is closely related, your activity will need to implement an Observer, your POJO will implement an Observable, and you will need to inject an update () method in your activity, this one will receive all updates no matter what you send the Observable.

Hope this makes sense a little :)

+3


source







All Articles