What is the meaning of void in the AsyncTask argument?

Asked 1 years ago, Updated 1 years ago, 97 views

public static class DownloadWorker extensions AsyncTask <Void, void, void{
    @ Override
        Protected String doInBackground (Void...voids) {
            return null;

java android android-layout android-asynctask

2022-09-30 16:53

1 Answers

You want to know what Void means in the type argument AsyncTask takes.

The code for the sample is probably incorrect.The following are considered positive:

public static class DownloadWorker extensions AsyncTast<Void, Void, String>{
    @ Override
    Protected String doInBackground (Void...voids) {
        return null;
    }
}

Three Voids appeared in the above code.The first Void corresponds to the type of doInBackground argument.The second Void corresponds to the type of callback method argument onProgressUpdate.Incidentally, the third argument corresponds to the type of doInBackground return value and the type of onPostExecute argument.

Based on the above, I will explain the above code.Since the first type argument is Void, the doInBackground argument is Void.In other words, doInBackground does not take action with arguments.Since the second type argument is also Void, the onProgressUpdate argument is also Void, and it does not take action using the argument.The third type argument is String, so doInBackground returns String.

With this knowledge, you can implement non-Void types.This is simple, but for example, the following code.

public static class DownloadWorker extensions AsyncTask<Uri, Integer, List<String>{
    @ Override
    Protected List <String > doInBackground (Uri...uris) {
        final List<String>list=new ArrayList<>();
        for(inti=0;i<uris.count;i++){
          final String content = HttpClient.download(uri); // HTTP communication to download data.Implementation omitted
          publishProgress(int)i+1/uris.count)// Express the progress of the task as an integer
          list.add(content);
        }
        return list;
    }

    @ Override
    protected onProgressUpdate(Integer...progress){
        // Display progress on ProgressBar, etc.
    }

    @ Override
    protected void onPostExecute(List<String>list) {
        // Update UI using list
    }
}

Exception handling is omitted, but it looks like this.Any method other than AsyncTask doInBackground is built on the assumption that it runs on the UI thread.This allows the inter-thread communication code to be implemented without the programmer implementing it.

See the reference for details.AsyncTask


2022-09-30 16:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.