Friday, April 10, 2015

AsyncTask

 - Allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
 - Should ideally be used for short operations. (use java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask for long running thread).
 - Define 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
 - Async Task uses ThreadPoolExecutor to run multiple tasks at same time. total thread size = CPU Count * 2 + 1.
 - AsyncTask must be subclassed to be used. 
 - The task instance must be created on the UI thread.
 - AsyncTask callback methods are thread safe.

Generic Types.
AsyncTask<Params, Progress, Result>

params....
execute(params....)  (ex: execute(url1, url2, url3))
params are passed to doInBackground method which is being executed in worker thread

Progress....
publishProgress(Progress...) being called inside doInBackground, Progress... value passed to method onProgressUpdate running in UI Thread.

result.....
return result.... return value from doInBackground passed to onPostExecute

Cancelling a Task.
isCancelled() returns true is task been cancelled using API cancel(boolean) 

Execution.
- Before DONUT - no thread pool in AsyncTask
- After DONUT - Thread Pool introduced and by default task are executed in multiple thread.
- After HONECOMP - by default tasks are being executed in single thread to avoid error. use executeOnExecutor(Executor exec, Params... params) API to enable true parallel execution.
- AsyncTask has two static Executor instance SERIAL_EXECUTOR & THREAD_POOL_EXECUTOR

0 comments:

Post a Comment