Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give a progressbar for the download?

In my application i'm downloading a video file. I want to show the progress bar for the download.

How is it possible through AsyncTask Concept?

Thanks,

Niki

like image 435
Niki Avatar asked Nov 27 '25 03:11

Niki


1 Answers

Use the onProgressUpdate method of AsyncTask.

If you know the size of the file you can set the max value in onPreExecute:

protected void onPreExecute() {
  ProgressDialog myDialog = new ProgressDialog(context);
  myDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  myDialog.setMax(maxValue);
  myDialog.show();
}

EDIT: added myDialog.show();

There are several methods to update the progress, either by incrementing by an amount or by setting the progress to a specific value:

@Override
protected void onProgressUpdate(Integer... progress) {
  myDialog.incrementProgressBy(progress[0]);

  // or
  // myDialog.setProgress(progress[0]);

}

Then in the onDoInBackground():

@Override
protected void doInBackGround() {
  // your code
  publishProgress(1);
}

EDIT example with progressbar in layout:

In your layout file, add a progressbar like this

<ProgressBar
    android:id="@+id/progressbar"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    style="?android:attr/progressBarStyleHorizontal"
    android:visibility="gone"
    />

And in your asynctask:

protected void onPreExecute() {
  ProgressBar myProgress = findViewById(R.id.progressbar);
  myProgress.setMax(maxValue);
  myProgress.setVisibility(View.VISIBLE);
}

protected void onProgressUpdate(Integer... progress) {
  myProgress.setProgress(progress[0]);
}
like image 115
Eric Nordvik Avatar answered Nov 29 '25 17:11

Eric Nordvik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!