A lot of Developers including have hard time at the beginning writing an AsyncTask because of the ambiguity of the parameters. The big reason is we try to memorize the parameters used 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.
AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.
ie
AsyncTask<Input,Progress,Output>
Just figure out what your Input, Progress and Output are and you will be good to go.
For example
How does
doInbackground()
changes withAsyncTask
parameters?
How
doInBackground()
andonPostExecute()
,onProgressUpdate()
are related?
How can You write this in a code?
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 in Your Activity?
new DownLoadTask().execute("Paradise.mp3");