Android Download Manager Example

Hey guy’s, today we’re going to learn how can we download a file, mp3, ppt or image from the internet with DownloadManager. Downloading a file from the internet is a basic need of the app right. So, with DownloadManager it’s very easy.

DownloadManager is an android system service that handles long-running HTTP downloads. Apps request for downloads by passing a URI or also tell the destination folder in where you want to store that specific file.

Note: DownloadManager only supports HTTP protocol.

So, enough of this theory let’s see how we can integrate DownloadManager in our Android app.

Android App Setup

First, start with the AndroidManifest file. Open the AndroidManifest file and add permission for internet and storage.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Below is code for the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/downloadImageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/download_image" />

    <Button
        android:id="@+id/downloadSongButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="@string/download_song" />

</LinearLayout>

This is a very simple UI. In this UI we have only two buttons one is for download image and another one is for download song from the server.

Now go MainActivity.java class and get these buttons reference and add ClickListener on these buttons.


findViewById(R.id.downloadImageButton).setOnClickListener(this);
findViewById(R.id.downloadSongButton).setOnClickListener(this);

Below is the abstract method of View.OnClickListener interface.

@Override
  public void onClick(View view) {
      switch (view.getId()) {
          case R.id.downloadImageButton: {
              startService(DownloadSongService.getDownloadService(this, IMAGE_DOWNLOAD_PATH, DirectoryHelper.ROOT_DIRECTORY_NAME.concat("/")));
              break;
          }
          case R.id.downloadSongButton: {
              startService(DownloadSongService.getDownloadService(this, SONG_DOWNLOAD_PATH, DirectoryHelper.ROOT_DIRECTORY_NAME.concat("/")));
              break;
          }
      }
  }

DownloadSongService is the IntentServiceWhen the button is clicked we start DownloadSongService. Another thing of noticeable here is the DirectoryHelper class. DirectoryHelper is the util class for storage permission. This util class helps us to create directories to store image and song.

Below is the DownloadSongService class.

public class DownloadSongService extends IntentService {

    private static final String DOWNLOAD_PATH = "com.spartons.androiddownloadmanager_DownloadSongService_Download_path";
    private static final String DESTINATION_PATH = "com.spartons.androiddownloadmanager_DownloadSongService_Destination_path";

    public DownloadSongService() {
        super("DownloadSongService");
    }

    public static Intent getDownloadService(final @NonNull Context callingClassContext, final @NonNull String downloadPath, final @NonNull String destinationPath) {
        return new Intent(callingClassContext, DownloadSongService.class)
                .putExtra(DOWNLOAD_PATH, downloadPath)
                .putExtra(DESTINATION_PATH, destinationPath);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        String downloadPath = intent.getStringExtra(DOWNLOAD_PATH);
        String destinationPath = intent.getStringExtra(DESTINATION_PATH);
        startDownload(downloadPath, destinationPath);
    }

    private void startDownload(String downloadPath, String destinationPath) {
        Uri uri = Uri.parse(downloadPath); // Path where you want to download file.
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);  // Tell on which network you want to download file.
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  // This will show notification on top when downloading the file.
        request.setTitle("Downloading a file"); // Title for notification.
        request.setVisibleInDownloadsUi(true);
        request.setDestinationInExternalPublicDir(destinationPath, uri.getLastPathSegment());  // Storage directory path
        ((DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE)).enqueue(request); // This will start downloading 
    }
}

We also need to configure our service in AndroidManifest.xml. If we do not add service to the Manifest file then the service never going to start.

The following shows you how you can add service tag in AndroidManifest.xml file.

<service
    android:name=".DownloadSongService"
    android:enabled="true"
    android:exported="false" />

That’s it guy’s if you want to see the complete example see it on GitHub. You guys must be thinking where is the DirectoryHelper class. I thought it might not good to explain about storage in DownloadManager tutorial but, you can see it on GitHub with the complete example.

I hope this blog gives you a good understanding of DownloadManager. If you’ve any queries please do comment below.

 

Topics, you might be interested: Android WorkManager Example

or Online Offline Audio Streaming With ExoPlayer

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here