WayWay WayWay - 1 year ago 103
Java Question

Android AsyncTask Parameters

I'm having trouble understanding the use of the parameters for Asynctask in android.

The Android Developers documentation explains it as follows:

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)

Here is an example of subclassing:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
return totalSize;

protected void onProgressUpdate(Integer... progress) {

protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");

Once created, a task is executed very simply:

new DownloadFilesTask().execute(url1, url2, url3);

For my extension of AsyncTask, I don't need to pass in any parameters, but I need to override the doInBackground, onProgressUpdate, and onPostExecute methods. Why do I have to insert Void,Void,Void into AsyncTask<>?
What do the parameters do?

Answer Source

From the documentation it says using Void simply marks the type as unused. You don't have to have a type in AsyncTask.

The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.

Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:

private class MyTask extends AsyncTask<Void, Void, Void> { ... }