Home » Android » android – Pattern to make AsyncTask "procedural"

android – Pattern to make AsyncTask "procedural"

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am using AsyncTask in a lot of places without issues.

Now with Honeycomb, all network i/o needs to be in thread separate from the UI thread, which in a lot of cases needs AsyncTasks in places, where before a synchronous network connection was well suited (Honeycomb will throw an Exception for any network i/o on the main/ui thread).

Now I would basically like to get something like Object result = MyAsyncTask().execute() are there good patterns for this?

I’ve found AsyncTask Android – Design Pattern and Return Values which makes sense and is also how GWT does things, but somehow this sounds like wagging the dog by the tail (and then it may just be me who’s brain needs some more twisting).

How to&Answers:

Yup. You’re close. Try

Object result = MyAsyncTask().execute().get();

Answer:

I’m sure that you’re not wanting to perform a synchronous network transaction on the UI thread, right?

The pattern that I use is to hold state in the Activity (which implements a receiver), then call AsycTask which performs a callback to your activity in onPostExecute() (i.e. fire an Intent which your activity is listening for). Your activity can then update the state according to extras in the intent, and continue processing. It’s basically a state machine held in your Activity which performs your login and other functions. All of the network I/O stuff is performed in AsycTask instances which cause the state to be updated as they complete.

Answer:

If you just want to block your thread, while other thread does the job, you could consider writing your own task abstraction. I am thinking of something like

public class MyTask <T>  {
    // define executor here
    public T execute(Callable<T> c) {
        Future<T> t = executor.submit(c);
        return t.get();
    }
 }