Asynchronous tasks that may return a value. This class is the base class for tasks executed into a separated thread and
allowing for a return value. AsyncTask is abstract; concrete subclass should implement
#execute() abstract method.
There are basically two usage patterns for handling the returned value: first is to override
#onPostExecute(Object)like in sample code below. Please note that value handling hook is executed in the same thread as task logic.
AsyncTask<Object> task = new AsyncTask<Object>() {
protected Object execute() throws Throwable {
// asynchronous task logic
}
protected void onPostExecute(Object value) {
// take some actions on task returned value
// executed in the same thread as execute()
}
};
task.start();
Second is supplying a
Callback implementation to asynchronous task constructor. After
#execute() completes,
Callback#handle(Object) is transparently invoked in the same thread on which task was executed.
AsyncTask<Object> task = new AsyncTask<Object>(callback) {
protected Object execute() throws Throwable {
// asynchronous task logic;
}
};
task.start();
Because of his nature, asynchronous logic exceptions are not directly accessible to caller thread. Once asynchronous thread
launched the caller thread has no chance to catch execution exceptions. To overcome this limitation this class supply
#onThrowable(Throwable) hook. If exception occur neither
#onPostExecute(Object) nor
Callback#handle(Object) are invoked.
AsyncTask<Object> task = new AsyncTask<Object>(callback) {
protected Object execute() throws Throwable {
// asynchronous task logic;
}
protected void onThrowable(Throwable throwable) {
// handle asynchronous execution exception
}
};
task.start();