Download a file with Android, and showing the progress in a ProgressDialog
To download a file with Android and show the progress in a ProgressDialog, you can use the following steps:
- Create a ProgressDialog and set the style to STYLE_HORIZONTAL:
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- Set the message and maximum value of the ProgressDialog:
progressDialog.setMessage("Downloading file...");
progressDialog.setMax(100);
- Show the ProgressDialog:
progressDialog.show();
- Create a URL object for the file you want to download and open a connection to it:
URL url = new URL("http://example.com/file.zip");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
- Get the size of the file and calculate the total number of bytes read:
int fileLength = connection.getContentLength();
int bytesRead = 0;
int percentCompleted = 0;
- Create a BufferedInputStream to read the data from the connection:
InputStream input = new BufferedInputStream(url.openStream());
- Create a FileOutputStream to save the downloaded data to a file:
OutputStream output = new FileOutputStream("/path/to/save/file.zip");
- Read the data from the input stream and write it to the output stream:
byte[] data = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
bytesRead += count;
percentCompleted = (int) ((bytesRead * 100) / fileLength);
progressDialog.setProgress(percentCompleted);
output.write(data, 0, count);
}
- Close the input and output streams:
input.close();
output.close();
- Dismiss the ProgressDialog:
progressDialog.dismiss();
Keep in mind that this is just a basic example, and there are many other considerations to take into account when implementing a file download in a real application, such as error handling, user input validation, and threading.