Reputation: 1181
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
Upvotes: 3
Views: 2705
Reputation: 14746
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]);
}
Upvotes: 6
Reputation: 3380
First you have to calculate downloading timi, and then implement progress bar as per time limit. here i enclosed the sample program of progress bar
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
And this is the code for calculating the Time length for downloading file
//once the connection has been opened
List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {
// getHeaderFields() returns a Map with key=(String) header
// name, value = List of String values for that header field.
// just use the first value here.
String sLength = (String) values.get(0);
if (sLength != null) {
//parse the length into an integer...
}
Upvotes: 0