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); 
Answer from Nirav Ranpara 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 - Here we will be simply adding the link of the file available online. When we click on the Button it will be downloaded automatically to our phone storage. This is a very frequently used feature as we can use this feature to automatically download ...
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))
}
Discussions

kotlin - How to download file from URL in android? - Stack Overflow
What is the best way to download file from url. I try to use DownloadManager. But I cannot understand how to get Uri of downloaded file . Here is my code: file?.let { val uri = Uri.p... More on stackoverflow.com
🌐 stackoverflow.com
downloading - How to download files from the Web in the Android Browser? - Android Enthusiasts Stack Exchange
For some Android browsers limitations, ... to download a picture from the browser, thanks. ... I've struggled with this same issue, though in my case I wanted to save a Text file (.txt) that I had open in the Chrome browser on Android 4.4.x (Kit Kat). After reading this and other questions posted I realised that neither Chrome, the Google applications, nor the standard Android tools would allow me to simply save a Text file from a URL... More on android.stackexchange.com
🌐 android.stackexchange.com
How to download file/image from url to your android app - Stack Overflow
I need my android app to make request to url to download an image from this url so I have built this class to help me, BUT it didn't work ??? public class MyAsnyc extends AsyncTask More on stackoverflow.com
🌐 stackoverflow.com
How to download a file from URL and save to public external directory using Storage Access Framework in Xamarin Android?
Currently, the Xamarin Android app uses GetExternalStoragePublicDirectory (deprecated as of API level 29) with the requestLegacyExternalStorage enabled to download a file from Azure Blob Storage endpoint into the downloads directory directly. The official way out of this is to use Storage Access Framework (SAF) and allow the user to select the destination to save the file. Registered a dependency service as follows: ... public void DownloadFile(string url... More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
🌐
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 › android-download-file-from-url-and-save-to-internal-storage.php
Android Download File From URL And Save To Internal Storage
The save function takes the information from edittext and stores it within a file in byte format. Here, Toast was also used to display the location of the file along with its name. The following function uses intent to advance to the subsequent action linked to it. This is how we can implement the URL and save it to internal storage. I hope this article on android download file from url and save to internal storage helps you and the steps and method mentioned above are easy to follow and implement.
🌐
42Gears
techblogs.42gears.com › home › android download file with data url
Android Download file with Data URL - Tech Blogs - 42Gears
July 23, 2024 - File destinationFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"download1."+extension); ... Example : data:Hello World! String source = URLDecoder.decode(myDataUrl).replaceAll("data:.+?,",""); BufferedOutputStream ...
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();
} 
Find elsewhere
Top answer
1 of 4
11

Nowadays the built-in Android browser has been replaced by Chrome, which does this perfectly well. You can long-press and save virtually any image or link, and even videos from a number of sites that couldn't be easily done on the desktop.

Answer below for older devices:

The Android browser by default can only download files that the Android system "recognizes" (i.e., there has to be a program registered to handle that file type). It's a stupid restriction in my opinion, but you can install Download Crutch to overcome this limitation (it registers itself for every filetype).

If you're referring to images that link to something else and you want to save the something else, long-press on the image and choose "Save Link As" or similar.

2 of 4
9

Personally I usually just click the link of the file and it downloads.

As for the image: try long pressing but instead of choosing "Save As" look for "Copy link URL" or "Open in New Window" or something similar to those two menu options. "Copy link URL" should copy the URL of the file to your clipboard, then you can paste that link in the address bar and hit "Go" and it should download your file. "Open in New Window" should essentially do the same thing (i'm just trying to give you as many options as I can to try). If you click on the link it may not take you anywhere but to a blank page while the file downloads.

So to check your download list: You may have already tried this but to see if the file was downloaded you can open your browser, open the menu, then select "More", you should see "Downloads". This is where your downloaded files list is.

Another way you could check is to look in the "downloads" folder on your sdcard (/sdcard/downloads/) using ES File Explorer or some other file explorer.

If this is not a solution let me know and give an example of what you are trying to accomplish and I'll try to figure it out.

🌐
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.
🌐
Firebase
firebase.google.com › documentation › cloud storage for firebase › download files with cloud storage on android
Download files with Cloud Storage on Android | Cloud Storage for Firebase
To download a file, first create a Cloud Storage reference to the file you want to download. You can create a reference by appending child paths to the root of your Cloud Storage bucket, or you can create a reference from an existing gs:// or https:// URL referencing an object in Cloud Storage.
🌐
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", ...
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"/> 
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 401421 › how-to-download-a-file-from-url-and-save-to-public
How to download a file from URL and save to public external directory using Storage Access Framework in Xamarin Android? - Microsoft Q&A
Currently, the Xamarin Android app uses GetExternalStoragePublicDirectory (deprecated as of API level 29) with the requestLegacyExternalStorage enabled to download a file from Azure Blob Storage endpoint into the downloads directory directly. The official way out of this is to use Storage Access Framework (SAF) and allow the user to select the destination to save the file. Registered a dependency service as follows: ... public void DownloadFile(string url, string fileName) { Intent intent = new Intent(Intent.ActionCreateDocument); intent.AddCategory(Intent.CategoryOpenable); intent.PutExtra(Intent.ExtraTitle, fileName); intent.PutExtra("download_url", url); intent.SetType("application/pdf"); var activity = MainActivity.Instance; activity.StartActivityForResult(intent, CREATE_PDF_REQUEST); }
🌐
YouTube
youtube.com › watch
How to download file from url in Android Studio. - YouTube
Subscribe Channel : https://www.youtube.com/channel/UCIRNmq6-UcySQZpyQHJwgkgOther Videos:1. how to log in and register using firebase in the android studio:h...
Published   March 10, 2021
🌐
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 - Finally, we’ll talk about how ... basic API we can use to download a file is Java IO. We can use the URL class to open a connection to the file we want to download....
🌐
Stack Overflow
stackoverflow.com › questions › 42627416 › android-download-file-from-url
get - Android download file from url - Stack Overflow
You can open it as text/html file and see what's going wrong ... it's because you are using Query parameter ##somewebsite.php?t=432513## , which return html page not the file. for downloading the file, the URL should have file in it.
🌐
Medium
medium.com › @bssss100 › download-save-open-any-file-on-android-with-download-manager-262c8842429a
Download, Save & Open any file on Android with Download Manager | by Sudhanshu Ranjan | Medium
April 15, 2024 - We are using Android’s Download Manager class to send a request to download our file by giving the URL and parsing it into the relevant URI.
🌐
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 · 中文 – 简体