How to add loading animation while another thread is running?

I use AsyncTask in my application. As far as I understand, I need to use the onProgressUpdate method in the flow class, but I don’t know how to interact with it. What do I need to do to show the download progress while the thread is running?

  • one
    How do you like this option: turn on the animation before downloading. At the moment when the download is complete, pull the newly created Handler, which turns off the animation. - George Chebotaryov

1 answer 1

It all depends on what kind of progress and how you want to show. If you studied the examples of working with AsyncTask, then you should know that the second class parameter is the type of the published result, i.e. The type of data that will be passed to the onProgressUpdate () method from the doInBackground method by calling the publishProgress () method.

Below is a sample code from the official documentation :

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) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } } 

Here AsyncTask itself loads the url. The publishProgress method transfers how many percent of the url has been loaded and in the onProgressUpdate method this percentage is somehow displayed in the interface.