W3docs

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:

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:

Note: ProgressDialog has been deprecated since API 26. For modern apps, use a ProgressBar inside a Dialog or MaterialAlertDialogBuilder.

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:

Note: connection.connect() is redundant and has been removed.

URL url = new URL("http://example.com/file.zip");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  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;

// Handle unknown file length to prevent division by zero
if (fileLength == -1) {
    fileLength = 0;
}
  1. Create a background thread to handle the download and update progress on the main thread:

Note: Use connection.getInputStream() instead of url.openStream() to avoid duplicate connections. Progress updates and dialog dismissal must run on the UI thread.

Thread downloadThread = new Thread(() -> {
    try (InputStream input = new BufferedInputStream(connection.getInputStream());
         OutputStream output = new FileOutputStream("/path/to/save/file.zip")) {
        
        byte[] data = new byte[1024];
        int count;
        
        while ((count = input.read(data)) != -1) {
            bytesRead += count;
            if (fileLength > 0) {
                percentCompleted = (int) ((bytesRead * 100) / fileLength);
            }
            
            // Update UI on the main thread
            runOnUiThread(() -> progressDialog.setProgress(percentCompleted));
            
            output.write(data, 0, count);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Dismiss dialog on the main thread
        runOnUiThread(() -> progressDialog.dismiss());
    }
});
downloadThread.start();

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, threading, and required permissions (e.g., INTERNET and storage permissions).