I don't understand what I am supposed to put in here and where these arguments end up? What exactly should I put, and where exactly will it go? Do I need to include all 3 or can I include 1,2,20?
This question is related to
android
arguments
android-asynctask
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");
in Short, There are 3 parameters in AsyncTask
parameters for Input use in DoInBackground(String... params)
parameters for show status of progress use in OnProgressUpdate(String... status)
parameters for result use in OnPostExcute(String... result)
Note : - [Type of parameters can vary depending on your requirement]
Refer to following links:
You cannot pass more than three arguments, if you want to pass only 1 argument then use void for the other two arguments.
1. private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>
2. protected class InitTask extends AsyncTask<Context, Integer, Integer>
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
KPBird
Source: Stackoverflow.com