Android Download Files & Save

Android Download Files & Save

In this tutorial we are going to learn how to download pdf, doc , video, mp3, zip ,etc. files from server and save them in device memory.

Below are certain things that we are going to learn in this tutorial :

 1. Download Files – Download Files from Server Url.

2. Save Files – Create Folder in device and save the dowloaded files.

3. Download Multiple Files – Download Many Files at a time.

VIDEO DEMO

1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.

2. Open res=>values=strings.xml and add the following strings to it.

3. Create a xml layout naming activity_main.xml and add the following code. In this  layout there are some Buttons for showing downloading different type of files.

4. Create a Utils.java class and write all download urls here.

5. Create a CheckForSDCard.java class for checking if SDCard is present or not.

6. Now create a DownloadTask.java and add the following code. In this code AsyncTask is used for downloading data from server. There are several main steps in doInBackground(Void…arg0) that are listed below :

1. Converting download url into URL:

2. Opening Url Connection for data downloading:

3. Setting request method to server:

4. Connect the open connection:

5. Create a directory in SD Card if not present:

6. Create an Output file i.e. download file inside above created directory:

Note: Give extension to your outputFile like .pdf, .mp3, .mp4 etc.

7. Download File and write it over the outputFile created:

8. Close all connection after downloading:

Full Code of DownloadTask.java

7. Now create MainActivity.java and add the following code. In this code i am starting AsyncTask on button click.
But before downloading it is necessary there should be a proper internet connection. So for this I had created a method naming isInternetConnected() that will return true or false.

If you are new in how to detect internet connection then check Detect Internet Connection Tutorial.

Last Button is for Opening  downloaded folder and the code for opening download folder is below:

Full MainActivity.java Code

8. Finally come to AndroidManifest.xml file and add below several permissions to Manifest file.

9. Finally, all done you can use above steps for downloading any kind of files.

Thanks. :)

Download Source Code

 

About the author

I am an Android developer for whom Android is the one and only love. I work as a freelancer which gets me and Android closer. I always love to share my learnings and love to learn from others knowledge too.

COMMENTS (51)
Reply

Not working. Shows IO Execption.

Reply

It worked, Thanks. But if I want to make it generic for creation of file with extension then how i we do it. How can I get extension from url for create new file of the same name.

Reply

It is possible to show the percentage of download for each file?

Reply

Hi, Thank you for your nice Tutorial. I have a problem. When I click on download buttons, show Download failed and download again. I set Permissions in Android Manifest.

Reply

Thanks. It worked. Downloaded files are store in internal storage but when i click on the downloaded folder to open all files are faded and i am unable to click on them.

    Hi Zoraiz,

    Fading issue is basically may be your device issue or may be you don’t have permission to access those files. Please try to change the location.

    Thanks

Reply

Error in code. You are trying to update UI from doInBackground. Try to use RunonUiThread to show Toast.

Reply

Dr Droid, Thanks so much, this was very useful.

@Kishor Singh, he is passing a context from the calling function which is being used while showing the Toast message, so there are no errors at runtime.

For those people who are seeing grayed out files here is what I did:
1. Modify the code to store the files in a Public Directory like ‘Download’ (in case you are ok sharing the file with other Apps) using the following call to get the location of the public directory:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
2. In phones like Nexus, browse the file using inbuilt application as follows: “Settings->Storage and USB->Explore->Download”. You will see the file without being grayed out.
Hope this helps.

Dr Droid, thanks once again for this wonderful website !!!

Reply

Thanks a lot, worked however I have noticed it’s failing to download bigger files. It’s working on small size files less than 1mb but tried 3mb files and failed.

Reply

Thanks a lot! Amazing tutorial. It seems that adding request permissions in the manifest file isn’t enough to write in my external memory so i just wanted to add that I had to make a modification in the onClick method of the MainActivity Class before the switch case:

//Before starting any download check if write permissions are granted
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Permission is not granted
Log.e(TAG , “WRITE EXTERNAL STORAGE PERMISSION NOT GRANTED”);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
return;

}

Reply

good job sir.

all code work perfectly.

but is it possible to download files from google drive

thanks in andvance

Reply

working good but when i change the link of files with my own ,then it fails to download.only the file from ur link is working, other link is not downloading…my url is correct

    Hi Sagar,

    Please change the main url also : public static final String mainUrl = “http://androhub.com/demo/”;

    Thanks

Reply

how toafter download file show listview file?
example file pdf
thanks

Reply

how to download all file in one folder?

    Hi Babang,

    The above given code is already downloading all files in single directory only.

    Thanks

Reply

Hello bro
TextView tv2 = tv_file;
final String testing = tv2.getText().toString();

public static final String downloadPdfUrl = “”;

i have url from testing and want donwloadPdfUrl can read textview testing.
how to read from testing?

Reply

public static final String downloadDirectory = “Androhub Downloads”;
i am not able to get the purpose of this line, sir can you please brief it?

    Hi Surendra,

    This line is basically a folder/directory that is going to create into your storage and all the downloaded files will gonna save into this folder/directory only.

    Thanks

Reply

Thank you sir for help! But now i am getting a new error.

W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
06-19 13:43:37.146 3690-3690/? E/Download Task: 12.pdf
06-19 13:43:45.518 3690-3690/? E/Download Task: 18.pptx
06-19 13:43:45.520 1692-1858/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
06-19 13:44:02.963 1692-1858/? W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
06-19 13:44:02.963 3690-3690/? E/Download Task: 31.mp4
06-19 13:44:03.594 3690-3716/? W/System.err: java.io.IOException: write failed: ENOSPC (No space left on device)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.IoBridge.write(IoBridge.java:502)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.io.FileOutputStream.write(FileOutputStream.java:186)
06-19 13:44:03.594 3690-3716/? W/System.err: at com.surendra.retrievefilespart2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:141)
06-19 13:44:03.594 3690-3716/? W/System.err: at com.surendra.retrievefilespart2.DownloadTask$DownloadingTask.doInBackground(DownloadTask.java:42)
06-19 13:44:03.594 3690-3716/? W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
06-19 13:44:03.594 3690-3716/? W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-19 13:44:03.594 3690-3716/? W/System.err: at java.lang.Thread.run(Thread.java:818)
06-19 13:44:03.594 3690-3716/? W/System.err: Caused by: android.system.ErrnoException: write failed: ENOSPC (No space left on device)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.Posix.writeBytes(Native Method)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.Posix.write(Posix.java:258)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.BlockGuardOs.write(BlockGuardOs.java:313)
06-19 13:44:03.594 3690-3716/? W/System.err: at libcore.io.IoBridge.write(IoBridge.java:497)
06-19 13:44:03.594 3690-3716/? W/System.err: … 9 more

    Hi Surendra,

    If you see error logs its clearly written that : Caused by: android.system.ErrnoException: write failed: ENOSPC (No space left on device). That means the downloaded file requires more space then space left in your device. So free-up some space then try.

    Thanks

Reply

ok thanks

    Hi Ada apa,

    If you want to change the file name before downloading that you can do it by changing downloadFileName value to anyone required.

    But if you want to do after download then you need to make a copy of downloaded file with different name.

    Thanks

Reply

How I use it browser Application. Because there is no fix URL address for any downloading file, video, images, etc. Please Sir help me.

Reply

how to display pdf from server ..?

Reply

hi sir, ı try yourcodes but when ı click download button, it says “download failed” on button text (I have no extarnal storage sd card on myphone ) and how to store downloaded files on internal storage(phone storage)?

Reply

hello myfriend, I click “download button” on app then nothing happen only write download failed where I did mistake pls help me :/

Reply

Bro i want your email id

    Hi Golam,

    You can find the email at top of the blog.

    Thanks

Reply

Hi bro, i want to download videos from facebook by java anroid. so how will i do? could you guide me please?

Reply

Hi bro,

thanks a lot for the great job you did. How can i make it for multi files on the same URL, and make all files downloaded with one button only?

Thanks

Reply

hi i want to video download to save in gallery what i can do?

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Name (required)
Email (required)