This is some working code I have for downloading a given URL to a given File object. The File object (outputFile) has just been created using new File(path), I haven't called createNewFile or anything.

private static void downloadFile(String url, File outputFile) {
  try {
      URL u = new URL(url);
      URLConnection conn = u.openConnection();
      int contentLength = conn.getContentLength();

      DataInputStream stream = new DataInputStream(u.openStream());

        byte[] buffer = new byte[contentLength];
        stream.readFully(buffer);
        stream.close();

        DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
        fos.write(buffer);
        fos.flush();
        fos.close();
  } catch(FileNotFoundException e) {
      return; // swallow a 404
  } catch (IOException e) {
      return; // swallow a 404
  }
}
Answer from Eric Mill on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › android › how-to-download-file-from-url-in-android-programmatically-using-download-manager
How to Download File from URL in Android Programmatically using Download Manager? - GeeksforGeeks
July 23, 2025 - Below is the code for the MainActivity.java file. ... import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button button; DownloadManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.download); button.setOnClickListener(new View.OnClickListener()
Top answer
1 of 6
55

This is some working code I have for downloading a given URL to a given File object. The File object (outputFile) has just been created using new File(path), I haven't called createNewFile or anything.

private static void downloadFile(String url, File outputFile) {
  try {
      URL u = new URL(url);
      URLConnection conn = u.openConnection();
      int contentLength = conn.getContentLength();

      DataInputStream stream = new DataInputStream(u.openStream());

        byte[] buffer = new byte[contentLength];
        stream.readFully(buffer);
        stream.close();

        DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
        fos.write(buffer);
        fos.flush();
        fos.close();
  } catch(FileNotFoundException e) {
      return; // swallow a 404
  } catch (IOException e) {
      return; // swallow a 404
  }
}
2 of 6
12

Permission

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />

Download Fuction Code

 public void downloadFile() {
        String DownloadUrl = audio1;
        DownloadManager.Request request1 = new DownloadManager.Request(Uri.parse(DownloadUrl));
        request1.setDescription("Sample Music File");   //appears the same in Notification bar while downloading
        request1.setTitle("File1.mp3");
        request1.setVisibleInDownloadsUi(false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request1.allowScanningByMediaScanner();
            request1.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        }
        request1.setDestinationInExternalFilesDir(getApplicationContext(), "/File", "Question1.mp3");

        DownloadManager manager1 = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        Objects.requireNonNull(manager1).enqueue(request1);
        if (DownloadManager.STATUS_SUCCESSFUL == 8) {
        DownloadSuccess(); 
        }
    }
🌐
Learnoset
learnoset.com › source-code › android-studio-examples › download-file-from-url-using-download-manager-android-studio
Learnoset - Android Studio Examples
package com.learnoset.testproject; import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Downloading file from URL using DownloadManager downloadFile("Your file Url here"); } private void downloadFile(String fileUrl) { DownloadManager.Request request = new Dow
🌐
Mobikul
mobikul.com › home › how we download file from url in android
How we download File from URL in android - Mobikul
April 22, 2017 - There are many methods to download files from the server. ... Use DownLoadManager class and many others. I am discussing with DownLoadManager, it is applied on the GingerBread or above version of applications. GingerBread brought a new feature, DownloadManager, which allows you to download files easily and delegate the hard work of handling threads, streams, etc. to the system. ... Reference: http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog
🌐
Talkerscode
talkerscode.com › howto › how-to-download-file-from-url-in-android-programmatically.php
How To Download File From URL In Android Programmatically
In order to download a file from ... needs to use the HttpURLConnection and InputStream class to connect to the server, download the file's contents, and then write the entire content to a local file on the device's storage...
🌐
Blogger
techicaltutorial.blogspot.com › 2020 › 03 › android-download-file-programmatically-example.html
android download file programmatically example - Android Tutorial
March 26, 2020 - strings) { String apkUrl = strings[0]; try { if (!outputFile.exists()) { notifyFromBackground("Downloading..."); URL url = new URL(apkUrl); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setDoOutput(true); c.connect(); file.mkdirs(); FileOutputStream fos = new FileOutputStream(outputFile); InputStream is = c.getInputStream(); byte[] buffer = new byte[2048]; int len1 = 0; while ((len1 = is.read(buffer)) != -1) { fos.write(buffer, 0, len1); } fos.close(); is.close(); } // Do the install notifyFromBackground("Installing..."); Intent promptInstall = new Intent(Intent.ACTION_VIEW
🌐
Medium
medium.com › @eliothijanoc › simple-way-to-download-and-read-files-on-android-api-28-3557e6d240e5
Simple way to download and read files on android API>28 | by Eliot Hijano | Medium
August 16, 2021 - Lets imagine we have to download a file in the background of our app. For this, we create an asynchronous task, which I will call “downloadPDFTask”. Instead of using the deprecated class AsyncTask, I will use my own class BaseTask. Don’t worry though, they do basically the same thing. In this task, the downloadManager requests a download from a given url address, and queues it on your phone’s download manager.
Find elsewhere
🌐
Medium
medium.com › mobile-app-development-publication › download-file-in-android-with-kotlin-874d50bccaa2
Download File in Android with Kotlin | by Elye - A Dev By Grace | Mobile App Development Publication | Medium
September 5, 2020 - Here I will show you how to download with some simple code sample. First and foremost, you need to enable your App to access to the internet · Add the below permission in your AndroidManifest.xml file.
Top answer
1 of 2
6

How to download file from Url

fun downloadPdf(baseActivity:Context,url: String?,title: String?): Long {
        val direct = File(Environment.getExternalStorageDirectory().toString() + "/your_folder")

        if (!direct.exists()) {
            direct.mkdirs()
        }
        val extension = url?.substring(url.lastIndexOf("."))
        val downloadReference: Long
         var  dm: DownloadManager
         dm= baseActivity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        val uri = Uri.parse(url)
        val request = DownloadManager.Request(uri)
        request.setDestinationInExternalPublicDir(
                "/your_folder",
                "pdf" + System.currentTimeMillis() + extension
        )
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        request.setTitle(title)
        Toast.makeText(baseActivity, "start Downloading..", Toast.LENGTH_SHORT).show()

        downloadReference = dm?.enqueue(request) ?: 0

        return downloadReference

    }

Bofore calling this method do check for Runtime permission:

Manifest.permission.WRITE_EXTERNAL_STORAGE
2 of 2
5

Please try this code

public void downloadPdf(String url, String sem, String title, String branch) {
Uri Download_Uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);

//Restrict the types of networks over which this download may proceed.
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//Set whether this download may proceed over a roaming connection.
request.setAllowedOverRoaming(false);
//Set the title of this download, to be displayed in notifications (if enabled).
request.setTitle("Downloading");
//Set a description of this download, to be displayed in notifications (if enabled)
request.setDescription("Downloading File");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, title + "_" + branch + "_" + sem + "Year" + System.currentTimeMillis() + ".pdf");

request.allowScanningByMediaScanner(); 
request. setNotificationVisibility(DownloadManager.Request. VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION)

//Enqueue a new download and same the referenceId
downloadReference = downloadManager.enqueue(request);

}

attach broadcast receiver

BroadcastReceiver attachmentDownloadCompleteReceive = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
        long downloadId = intent.getLongExtra(
                DownloadManager.EXTRA_DOWNLOAD_ID, 0);
        openDownloadedAttachment(context, downloadId);
    }
}
};


private void openDownloadedAttachment(final Context context, final long downloadId) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
    int downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
    String downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    String downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
    if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
        openDownloadedAttachment(context, Uri.parse(downloadLocalUri), downloadMimeType);
    }
}
cursor.close();
} 
Top answer
1 of 16
95

Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }

    /**
     * Showing Dialog
     * */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
2 of 16
72

Simple kotlin version

fun download(link: String, path: String) {
    URL(link).openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            input.copyTo(output)
        }
    }
}

is there anyway to get the download progress or downloaded size from this method ?

This is the same realization as defined in InputStream.copyTo, but with progress

/*inline*/ fun download(link: String, path: String, progress: ((Long, Long) -> Unit)? = null): Long {
    val url = URL(link)
    val connection = url.openConnection()
    connection.connect()
    val length = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) connection.contentLengthLong else
        connection.contentLength.toLong()
    url.openStream().use { input ->
        FileOutputStream(File(path)).use { output ->
            val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
            var bytesRead = input.read(buffer)
            var bytesCopied = 0L
            while (bytesRead >= 0) {
                output.write(buffer, 0, bytesRead)
                bytesCopied += bytesRead
                progress?.invoke(bytesCopied, length)
                bytesRead = input.read(buffer)
            }
            return bytesCopied
        }
    }
}

An example of usage:

val handler = object : Handler(Looper.getMainLooper()) {

    override fun handleMessage(msg: Message) {
        // length may be negative because it is based on http header
        val (progress, length) = msg.obj as Pair<Long, Long>
    }
}

// call this outside of main thread
val totalSize = download("http://example.site/path/to/file", "path/to/file") { progress, length ->
    // handling the result on main thread
    handler.sendMessage(handler.obtainMessage(0, progress to length))
}
🌐
TutorialsPoint
tutorialspoint.com › how-to-download-and-save-an-image-from-a-given-url-in-android
How to download and save an image from a given URL in android?
July 3, 2020 - <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/coordinatorLayout" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btnDownload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Download Image" android:layout_margin="25dp" android:layout_gravity="top|center_horizontal" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="centerCrop" app:layout_anchor="@id/btnDownload" android:layout_gravity="bottom" app:layout_anchorGravity="bottom" android:layout_margin="10dp" /> </android.support.design.widget.CoordinatorLayout>
🌐
Stack Overflow
stackoverflow.com › q › 1714761
Newest Questions - Stack Overflow
Stack Overflow | The World’s Largest Online Community for Developers
🌐
The Code City
thecodecity.com › home › android › download pdf from any url in android studio – solution
Download PDF From Any URL in Android Studio – Solution
May 13, 2023 - You can easily download a PDF file from any URL using one of the following two methods. If you want to download the file within the app using DownloadManager...
🌐
Baeldung
baeldung.com › home › java › java io › download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - AsyncHttpClient is a popular library for executing asynchronous HTTP requests using the Netty framework. We can use it to execute a GET request to the file URL and get the file content.
🌐
Android Developers
developer.android.com › api reference › downloadmanager
DownloadManager | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
GeeksforGeeks
geeksforgeeks.org › kotlin › download-image-from-url-in-android
Download Image From URL in Android - GeeksforGeeks
July 23, 2025 - { try { return URL(string) } catch (e: MalformedURLException) { e.printStackTrace() } return null } // Function to save image on the device. // Refer: https://www.geeksforgeeks.org/kotlin/circular-crop-an-image-and-save-it-to-the-file-in-android/ private fun mSaveMediaToStorage(bitmap: Bitmap?)
🌐
Sanfoundry
sanfoundry.com › java-android-program-download-file-service
How to Download File using Service in Android? - Sanfoundry
June 16, 2022 - package com.example.download_file_service; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import android.app.Activity; import android.app.IntentService; import android.content.Intent; import android.os.Environment; public class DownloadService extends IntentService { private int result = Activity.RESULT_CANCELED; public static final String URL = "urlpath"; public static final String FILENAME = "filename"; public static final String FILEPATH = "filepath"; public static final String RESULT = "result"; public static final String NOTIFICATION = "service receiver"; public DownloadService() { super("DownloadService"); } // Will be called asynchronously by OS.