Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 399
wyatt Avatar asked Aug 05 '13 23:08

wyatt


1 Answers

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..

like image 131
Sushil Avatar answered Oct 23 '22 00:10

Sushil