Brien Colwell
Brien Colwell

Reputation: 396

What are good strategies for handling asynchronous callbacks on Android?

An app may have parts that run on separate threads and call back to some object when finished. A typical pattern may look like:

1) a View or Fragment makes a call to some model. The call originates from some View or Fragment

model.doSomething(context, new Runnable() {
    public void run() { /* run on the main thread when model finishes */ }
});

2) a model uses a Thread or AsyncTask that does something and then calls the callback on the calling thread - using a Handler

void doSomething(Context context, Runnable callback) {
    Handler handler = new Handler();
    // ...
    // When finished (this is really done on some separate thread),
    handler.post(callback);
} 

3) the callback interacts with calling View or Fragment to advance through some control logic

The callback may be touching state of a View that's not attached to a window, which may lead to instability in the app.

What are some good strategies to handle this situation?

Upvotes: 4

Views: 1131

Answers (1)

Stephan Leroux
Stephan Leroux

Reputation: 761

It sounds like you want to handle communication between your Model and your View in a more consistent manner. A good way to separate these is to use a Service:

http://developer.android.com/reference/android/app/Service.html

If you're app is only running in a single process, I would suggest looking into the IntentService since its much simpler to use.

A great example of this is the Google IO 2011 IOSched app:

http://code.google.com/p/iosched/

It seems pretty large but the architecture is well thought out with regards to separating data concerns (either from local or remote resources).

The second benefit of having this run in it's own service rather than binding a callback in your view is that the service lives outside the activity's lifecycle so you don't have to worry about what happens to your callback whenever your activity is destroyed/paused. Lots of times when using callbacks like these the callback will get invoked and the activity may not still be alive.

Upvotes: 1

Related Questions