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; ... { 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 ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 14998212 โ€บ how-to-open-downloaded-file-in-android-programatically
java - How to open downloaded file in Android programatically? - Stack Overflow
@Override protected Void ... } URL url = new URL(DownloadUrl); //you can write here any link File file = new File(dir, fileName); long startTime = System.currentTimeMillis(); Log.d("DownloadManager", "download begining"); Log.d("DownloadManager", "download url:" + url); Log.d("DownloadManager", "downloaded file name:" + fileName); /* Open a ...
๐ŸŒ
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...
๐ŸŒ
Mobikul
mobikul.com โ€บ home โ€บ how we download file from url in android
How we download File from URL in android - Mobikul
April 22, 2017 - 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
๐ŸŒ
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
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>
๐ŸŒ
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 - Learning Android Development Download File in Android with Kotlin Download with feedback of progress in Kotlin Sometimes we need to download files in our Android App, e.g. to display a PDF file. The โ€ฆ
๐ŸŒ
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...
๐ŸŒ
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/ ...
๐ŸŒ
CodingTechRoom
codingtechroom.com โ€บ question โ€บ how-to-download-part-of-file-url-android
How to Download a Specific Portion of a File from a URL in Android - CodingTechRoom
try { // URL of the file to be downloaded URL url = new URL("https://example.com/largefile.zip"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Specify the range of bytes to download connection.setRequestMethod("GET"); connection.setRequestProperty("Range", ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 27930018 โ€บ android-download-from-url
Android: Download from URL - Stack Overflow
private class DownloadTask extends AsyncTask<String, Integer, String> { private Context context; public DownloadTask(Context context) { this.context = context; } @Override protected String doInBackground(String... sUrl) { InputStream input = null; OutputStream output = null; HttpURLConnection connection = null; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // expect HTTP 200 OK, so we don't mistakenly save error report // instead of the file if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned
Top answer
1 of 4
3

try this

public class MyAsnyc extends AsyncTask<Void, Void, Void> {
    public static File file;
    InputStream is;

    protected void doInBackground() throws IOException {

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        file = new File(path, "DemoPicture.jpg");
        try {    
            // Make sure the Pictures directory exists.
            path.mkdirs();

            URL url = new URL("http://androidsaveitem.appspot.com/downloadjpg");
            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
             * Define InputStreams to read from the URLConnection.
             */
            is = ucon.getInputStream();

            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

        } catch (IOException e) {
            Log.d("ImageManager", "Error: " + e);
        }
    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        try {
            doInBackground();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute() {
        try {
            // Tell the media scanner about the new file so that it is
            // immediately available to the user.
            MediaScannerConnection.scanFile(null,
                    new String[]{file.toString()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
2 of 4
3

Define these on the top side

Button BtnDownload;

DownloadManager downloadManager;

After, You should write on create inside :

BtnDownload = (Button)findViewById(R.id.button1);

Later, You should write to the button's click event

downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);

Uri uri = Uri.parse("your url");

DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

Long reference = downloadManager.enqueue(request);

Finally, you need to add this onto the application tag to the manifest.xml :

<uses-permission android:name="android.permission.INTERNET"/> 
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 21672455 โ€บ how-to-download-a-file-programmatically-and-show-it-as-a-download-in-android
How to download a file programmatically and show it as a download in Android - Stack Overflow
I've tried to download that file in many places but it isn't showing. How can I "publish" that file as a Download? ... You can open your target file url in browser and it will be downloaded to device and it will be shown in downloads