I am going to download a file from my server in for which i have to draw a progress bar in % for showing that how much time is remaining and what % has been downloaded. Please tell me how can I do this.
-
1Check http://stackoverflow.com/questions/5041978/implement-progress-bar-for-file-download-in-android, and this http://stackoverflow.com/questions/11470656/android-download-file-from-server-and-show-the-download-progress-in-the-notific, as well.. – Arshad Ali Feb 22 '14 at 05:01
1 Answers
I'm not sure which parts you're having trouble with... downloading the file? getting an indication on the progress? updating the UI?
Here's a small walk though to get you through the steps:
The following code will show you to do perform the connection to server to get the file's input stream. I like to use HttpRequest to perform this sort of thing.
String url = "www.thefilelocation.com";
HttpGet httpRequest = new HttpGet(url);
HttpParams parameters = new BasicHttpParams();
// set any params you like, like timeouts, etc.
HttpClient httpClient = new DefaultHttpClient(parameters);
HttpResponse response = httpClient.execute(httpRequest);
InputStream inputStream = response.getEntity().getContent();
Header contentLengthHeader = response.getFirstHeader("Content-Length");
long contentLength = Long.parseLong(contentLengthHeader.getValue());
String fileNameAndPath = "<some file name and path>";
saveFileWithProgressIndication(inputStream, contentLength, fileNameAndPath);
Keep in mind that this code is synchronous, so you may want to play this in the background using a separate thread or Async task.
This code will get you the input stream, but won't download the file yet. The next code will show you how to download the file and monitor the progress.
private void saveFileWithProgressIndication(InputStream inputStream, long contentLength, String fileNameAndPath) throws IOException
{
File myFile = new File(filename);
FileOutputStream fout = null;
int totalSize = 0;
try
{
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
while ((count = inputStream.read(data, 0, 1024)) != -1)
{
fout.write(data, 0, count);
totalSize += count;
if (contentLength> 0)
updateProgressInUi((double)totalSize / (double)contentLength);
}
}
finally
{
if (inputStream != null)
inputStream.close();
if (fout != null)
fout.close();
}
}
This method will actually perform the file download. Every 1024 bytes downloaded will trigger a call to the update UI method (you can tinker with this however you like). The final piece is to update the UI:
private void updateProgressInUi(double percentage) // percentage will be between 0 and 1
{
runOnUiThread(new Runnable()
{
void run()
{
myLabel.setText( ((int)(percentage * 100)) + "%" );
}
});
}
You can easily change this to update the value of a progress bar, or anything else you had in mind.
Hope this helps :)

- 16,633
- 4
- 47
- 58