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

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

Leave a Comment