How to use asynctask to display a progress bar that counts?

In my application, I want the user to click a button and then wait 5 minutes. I know that sounds awful, but just go with him. The time remaining for 5 minutes of waiting should be shown on the progress bar.

I used a CountDownTimer with a text view for the countdown, but my boss wants something that looks better. therefore, reasoning about the step of progress.

+6
source share
1 answer

You can do something like this.

public static final int DIALOG_DOWNLOAD_PROGRESS = 0; private ProgressDialog mProgressDialog; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("waiting 5 minutes.."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(false); mProgressDialog.show(); return mProgressDialog; default: return null; } } 

Then write an async task to update the progress.

 private class DownloadZipFileTask extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected String doInBackground(String... urls) { //Copy you logic to calculate progress and call publishProgress("" + progress); } protected void onProgressUpdate(String... progress) { mProgressDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected void onPostExecute(String result) { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); } } 

That should solve your goal, and it doesn't even block the slot of the UI.

+34
source

Source: https://habr.com/ru/post/951082/


All Articles