7

In my application i want the user to press a button and then wait 5 mins. i know this sounds terrible but just go with it. The time remaining in the 5 min wait period should be displayed in the progress bar.

I was using a CountDownTimer with a text view to countdown but my boss wants something that looks better. hence the reasoning for a progress bar.

wyatt
  • 495
  • 2
  • 6
  • 16

1 Answers1

36

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

This should solve your purpose and it wont even block UI tread..

Geobits
  • 22,218
  • 6
  • 59
  • 103
Sushil
  • 8,250
  • 3
  • 39
  • 71
  • Please accept the answer if it solved your purpose. It will help others to identify right answer. thanks – Sushil Aug 06 '13 at 01:11
  • 1
    change the second parameter of AsyncTask to Integer than you don't need to parse progress[0] to Integer.. and just write simply publishProgress(progress) without "" + – Zar E Ahmer May 16 '14 at 06:29
  • 3
    deprecated: http://stackoverflow.com/questions/10285047/showdialog-deprecated-whats-the-alternative – Ed_ Aug 15 '14 at 17:26
  • As its not overly obvious in this answer, the second paramter in `extends AsyncTask` dictates what the expected parameters are for `onProgressUpdate` and `publishProgress`. You also need to override the method – Joe Maher Dec 01 '15 at 08:20