Download file from url in android using retrofit

Downloading files from a url is a common use case these days for a countless number of apps. The files to be downloaded can be of smaller size or bigger size depending on the app requirements. We will be checking how to download a bigger sized file in this tutorial.

We will be using retrofit 2 as our network client in this tutorial.

So first of all, go ahead and add the following dependencies in your newly created android studio project. Be sure that you add the dependencies in your app level build.gradle file and not the project level build.gradle file :

implementation 'com.squareup.retrofit2:retrofit:2.3.0'

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

Now go to your AndroidManifest.xml file and add the following two permissions inside it

The android.permission.WRITE_EXTERNAL_STORAGE permission is required to write the downloaded file to android storage whereas the permission android.permission.INTERNET is to make a network call over the internet to fetch the url to download.

First of all create an interface for the network calls which will interact with the network endpoints. See below code :

In the above code you can notice the @Streaming annotation which will help us to access the raw data which can be processed as streams of data. This data may be bigger than our android's disk space and will help to prevent the data from directly getting downloaded into our device storage. Instead of moving the data directly into the storage we can process the data accordingly and then write to disk accordingly.

If you check here you can see that WRITE_EXTERNAL_STORAGE is listed as a dangerous permission and hence we will need to check runtime permissions for these cases.