An AsyncTask
is background task which runs in the background thread. It takes an Input, performs Progress and gives Output.
ie
AsyncTask<Input,Progress,Output>
.
In my opinion the main source of confusion comes when we try to memorize the parameters in the AsyncTask
.
The key is Don't memorize.
If you can visualize what your task really needs to do then writing the AsyncTask
with the correct signature would be a piece of cake.
Just figure out what your Input, Progress and Output are and you will be good to go.
doInBackgound()
method is the most important method in an AsyncTask
because
AsyncTask
parameters.So lets see the relationship
doInBackground()
andonPostExecute()
,onProgressUpdate()
are also related
Show me the code
So how will I write the code for DownloadTask?
DownloadTask extends AsyncTask<String,Integer,String>{
@Override
public void onPreExecute()
{}
@Override
public String doInbackGround(String... params)
{
// Download code
int downloadPerc = // calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... params)
{
// show in spinner, access UI elements
}
}
How will you run this Task
new DownLoadTask().execute("Paradise.mp3");