Android Retrofit Download Image Progress Notification With Examples

In this tutorial, we’ll be using the Retrofit library in order to download an image from a URL. We will show the progress of the download in the notification task. We’ll be using an image from unsplash.com.

Android Retrofit Download Image

In our previous tutorial, we built an android application which we download a file using Retrofit and show the progress in the ProgressBar.

In order to build the app which downloads in the background and shows and updates the download progress in the Notification we need to do the following things:

  • Create an Intent Service.
  • Handle the download logic and notification creations inside it.
  • Create a Broadcast Receiver in our Activity to listen to updates from the Intent Service.
  • Once the download is complete, save the file to the disk.
  • Retrieve the File(image in this case) in your Activity.
  • Use Picasso to display it onto the Screen.

Project Setup

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

Add the following permissions in your AndroidManifest.xml file

Android Retrofit Download Image Progress in Notification Project Structure

android-retrofit-background-download-progress-notification-project (1)

Code

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

The code for the RetrofitInterface.java is given below.

The code for the MainActivity.java class is given below:

In the above code, we start the BackgroundNotificationService.java IntentService when the FloatingActionButton is clicked.

Before that, we check for the Runtime Permissions.

We’ve also created and registered an implicit BroadcastReceiver.

When the download would get completed it would send a message to the BroadcastReceiver via Intents.

Once the download is successfully completed we retrieve the saved file from the Internal Storage and display it in the ImageView using Picasso.

Let’s look at the BackgroundNotificationService.java class where all the download stuff is happening:

Inside the onHandleIntent we create the Notification first and then Retrofit instance.

Inside the Retrofit call, we do the download stuff and update the progress on the Notification.
To show a ProgressBar inside the Notification you just need to call setProgress on the Notification Builder instance.

sendProgressUpdate sends the update to the Broadcast Receiver.

Since Android Oreo, to build Notifications, we must use NotificationChannels.

The output of the above application in action is given below:

android retrofit background download progress notification demo

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

By admin

Leave a Reply

%d bloggers like this: