+ // The actual network request is in a `try` bracket so that `disconnect()` is run in the `finally` section even if an error is encountered in the main block.
+ try {
+ // Get the content length header, which causes the connection to the server to be made.
+ String contentLengthString = httpUrlConnection.getHeaderField("Content-Length");
+
+ // Make sure the content length isn't null.
+ if (contentLengthString != null) { // The content length isn't null.
+ // Convert the content length to an long.
+ fileSize = Long.parseLong(contentLengthString);
+
+ // Format the file size for display.
+ formattedFileSize = NumberFormat.getInstance().format(fileSize);
+ } else { // The content length is null.
+ // Set the file size to be `-1`.
+ fileSize = -1;
+ }
+
+ // Get the response body stream.
+ InputStream inputStream = new BufferedInputStream(httpUrlConnection.getInputStream());
+
+ // Initialize the conversion buffer byte array.
+ // This is set to a megabyte so that frequent updating of the snackbar doesn't freeze the interface on download. <https://redmine.stoutner.com/issues/709>
+ byte[] conversionBufferByteArray = new byte[1048576];
+
+ // Initialize the downloaded kilobytes counter.
+ long downloadedKilobytesCounter = 0;
+
+ // Define the buffer length variable.
+ int bufferLength;
+
+ // Attempt to read data from the input stream and store it in the output stream. Also store the amount of data read in the buffer length variable.
+ while ((bufferLength = inputStream.read(conversionBufferByteArray)) > 0) { // Proceed while the amount of data stored in the buffer in > 0.
+ // Write the contents of the conversion buffer to the file output stream.
+ outputStream.write(conversionBufferByteArray, 0, bufferLength);
+
+ // Update the downloaded kilobytes counter.
+ downloadedKilobytesCounter = downloadedKilobytesCounter + bufferLength;
+
+ // Update the file download progress snackbar.
+ publishProgress(downloadedKilobytesCounter);
+ }
+
+ // Close the input stream.
+ inputStream.close();
+ } finally {
+ // Disconnect the HTTP URL connection.
+ httpUrlConnection.disconnect();
+ }