About Android UI main thread:
Android handles the task/process on a Single User Interface Model (UI) which is
known as Main thread.
Main Thread cannot handle multiple tasks at a time also
cannot handle long process which is time consuming. It can only execute one
task at a time.
What is Async Task?
AsyncTask is the abstract class provided by android, which
is use to perform long background operations and show the results on the Main
UI thread.
When to use AsyncTask?
Suppose if you want to do network operation or download an
image/song. Now if you implement this without using AsyncTask, explicitly it
will get executed on Main Thread.
Hence the above operations are long, so uptill the time is
awaited to complete that long operation t complete, so the screen becomes
un-responsive. So to overcome this drawback, we can create a new thread and
perform these operations on the newly created thread, so the UI remains
responsive.
So here we need to use AsyncTask for creating the new thread
and perform the long operations in background and return the results to the
Main Thread as soon as the operation completes.
- doInBackground: Within this method you need to write the code for execution and return the result.
- onPostExecute: This method is called after the completion of doInBackground method, results from doInBackground is passed here as parameters.
- onPreExecute: This method is called before the doInBackground, here you can place progress bar.
- onProgressUpdate: This method can be called anytime from doInBackground by calling publisProgress.
Parameters of AsyncTask:
/* Public class abc extends AsyncTask<Void,Void,Void>
Now these 3 parameters of AsyncTask <Void,Void,Void>
stands for as follows:
- params
- progress
- result
Params:
params is the parameter passed from outside class, to the doInBackground class.
params is the parameter passed from outside class, to the doInBackground class.
Progress:
Progress is invoked anytime by doInbackground using PublishProgress to inform the Main Thread about the progress of the task.
Result:
It is returned by doInBackground , and onPostExecute take it as parameters.
Hope you enjoyed reading it, soon i will post a video tutorial for the AsyncTask with example.
Learn and stay tuned for more fun.
No comments:
Post a Comment