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).
Yup. You're close. Try
Object result = MyAsyncTask().execute().get();
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.
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();
}
}
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