Android AsyncTask Publishing progress

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Sometimes, we need to update the progress of the computation done by an AsyncTask. This progress could be represented by a string, an integer, etc. To do this, we have to use two functions. First, we need to set the onProgressUpdate function whose parameter type is the same as the second type parameter of our AsyncTask.

class YourAsyncTask extends AsyncTask<URL, Integer, Long> {
    @Override
    protected void onProgressUpdate(Integer... args) {
        setProgressPercent(args[0])
    }
}

Second, we have to use the function publishProgress necessarily on the doInBackground function, and that is all, the previous method will do all the job.

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));
     }
     return totalSize;
 }


Got any Android Question?