AsyncTask (abstract class)
Android defines AsyncTask as “a class that extends the Object class to allow short operations to run asynchronously in the background.” With “doInBackground” and “onPostExecute,” Async can run tasks asynchronously on new threads. Asynchronous tasks use: Params, parameters that are sent to the task upon execution.
Android defines AsyncTask as “a class that extends the Object class to allow short operations to run asynchronously in the background.” With “doInBackground” and “onPostExecute,” Async can run tasks asynchronously on new threads. Asynchronous tasks use: Params, parameters that are sent to the task upon execution.
- Enables proper and easy use of UI thread.
- Allow to perform operations in background and publish result on UI thread without having to manipulate threads and/or handlers.
- Async task is designed to be helper class around thread and handler.
- AsyncTask should ideally be used for a short operations. (few second at most) .
- It is defined by 3 generics type: Params, Progress, Result.
- And 4 step called onPreExecute, doInBackground (this step can also use publishProgress(...) one or more units on progress ), onProgressUpdate, onPostResult.
- To mark a type as unused by passing Void simply.
- A task can be cancel at any time by invoking cancel(boolean), invoking this method will cause subsequent calls to isCanceled() to return true. onCanced(Object) instead of onPostExecute(Object) will be invoked.
- The AsyncTask must be load on the UI thread. (automatically done as of JELLY_BEAN)
- The Asynctask instance must be create on the UI thread.
- execute(params...) must be invoked on the UI thread.
- Don’t call its 4 step method manually.
- The task can be execute only once (one instance), second execution will throw an exception.
- The AsyncTask guarantees that all callback calls are synchronized in a such way- fields constructor, onPreExecute (set member ) → refer them→ doInBackground (set member ) → refer them → onProgressUpdate or onPostExecute.
- When in first introduced, AsyncTask were executed serially on a single background thread with DONUT.
- This was changed to a pool of threads allowing multiple task operate in parallel, from HONEY_COMB.
- If you truly want parallel execution invoke executeOnExecutor(Executor, Object[]) with THREAD_POOL_EXECUTOR.
- SERIAL_EXECUTOR: an Executor that executes tasks one at time in serial order. The serialization is global to a particular process.
- THREAD_POOL_EXECUTOR an Executor that can be use to execute task in parallel.
- If you need to keep running threads for long periods of time, it highly recommend to use other api, Executor, ThreadPoolExecutor, FutureTask..
Comments
Post a Comment