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:

  1. Create a ProgressDialog and set the style to STYLE_HORIZONTAL:
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  1. Set the message and maximum value of the ProgressDialog:
progressDialog.setMessage("Downloading file...");
progressDialog.setMax(100);
  1. Show the ProgressDialog:
progressDialog.show();
  1. 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();
  1. Get the size of the file and calculate the total number of bytes read:
int fileLength = connection.getContentLength();

int bytesRead = 0;
int percentCompleted = 0;
  1. Create a BufferedInputStream to read the data from the connection:
InputStream input = new BufferedInputStream(url.openStream());
  1. Create a FileOutputStream to save the downloaded data to a file:
OutputStream output = new FileOutputStream("/path/to/save/file.zip");
  1. 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);
}
  1. Close the input and output streams:
input.close();
output.close();
  1. 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.