Android Publishing progress


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> {
    protected void onProgressUpdate(Integer... args) {

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;