Publishing progress

suggest change

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. setProgressPercent is not an AsyncTask method. It stands in for whatever updates the UI.

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

Second, call publishProgress from doInBackground. That is all. The previous method does the rest.

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;
 }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents