In this tutorial, we’ll create an android application which downloads a file from the URL using Retrofit.

To know the basics of Retrofit, visit this tutorial.

Android Retrofit Download File

We can create a retrofit call in the following way in order to download file:

We can pass the URL of the file we want to download. If we are downloading a file present in the resources we can do this:

It’s recommended to use a @Streaming annotation on top of the @GET for downloading files. Otherwise Retrofit would move the entire file into memory. Using @Streaming the bytes would be accessed currently without eating up the memory.

When using @Streaming you must add the code that writes the downloaded data, into a separate thread.

Using the enqueue method we can start the request.
Inside it, we need to create an AsyncTask or use RxJava. We’ll go with the former in this tutorial.

In the following android application that we are going to build, we’ll show the file download progress on a ProgressBar.

Project Setup

Add the following dependencies to your app’s build.gradle:

Add the following permissions in your Manifest:

Following is how our Project Structure looks:

android-retrofit-file-download-progress (1)


The code for the activity_main.xml layout is given below:

We’ve set a style on the button in the styles.xml.

The code for the class is given below:

The code for the class is given below:

In the above code, we are downloading a GitHub repository zip file.

We do the following list of things in the above code:

  • Runtime Permissions – We need this for saving the file in our phone storage.
  • Building a Retrofit Service using OkHttp
  • Downloading the file from the url in the Async by using response.body().
  • Inside the AsyncTask, we create a public method doProgress in which we invoke the AsyncTask method publishProgress().
  • publishProgress triggers the onProgressUpdate() method of AsyncTask from the doInBackground.
  • Doing so we can determine the progress of the file download and update it on the ProgressBar.
  • The downloaded file path is set inside the downloads folder in the Internal Storage.

The output of the application in action is given below:

android retrofit download file progress output

And a screenshot from our File manager proves that the file is downloaded:

android-retrofit-file-download-progress (1)

This brings an end to this tutorial. You can download the project from the link below:

By admin

Leave a Reply

%d bloggers like this: