Downloading files in background using download manager in android

In one of the previous article i am already explaining how to download the files in android which is an async task operation which will download the file and save it in your sd card. But what if it is bigger size file like a csv file with huge set of data which needs to be synced with your sqlite database or some compressed folder which is a set of images,in that case you cannot make the user to wait till the download is completed.

In this situation what you can do is you can take the entire task to background, without interrupting the foreground activity and not showing any progress dialog. And you can see the progress of download in the notification .This task is performed using Download manager in android. In this tutorial we will learn how to implement file using download manager in android.

Contents

  • Add required permissions
  • Implement function for downloading file using download manager
  • How to notify the app or activity once download is completed.
  • How to access the downloaded file.
  • How to share the downloaded file
download-manager

Add required permissions

Here in this example we are accessing the external directory and the file is downloaded from the url. So we definitely need read and write storage permission and internet connection permission, For having the permissions you need to add the following code into your AndroidManifest.xml file.

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

Note

If you are using target version greater than 21 you need to get the permissions on run time from the user. The tutorial Android request permission dynamically will explain how to get run time permission in android from user.

Implement function for downloading file using download manager

Downloading file using Download manager is much simpler operation than downloading file using async task. You can achieve it using a small set of code. Here we will create a function which will do this operation and you can use that inside your onCreate function or any other action you need to trigger the download.

private long DownloadData() {
long output;
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("url of the file needs to be downloaded"));
request.setTitle("Your download title");
request.setDescription("Your description");
//Setting the location to which the file is to be downloaded
request.setDestinationInExternalFilesDir(YourActivity.this, Environment.DIRECTORY_DOWNLOADS, "your-filename.ext");
output = downloadManager.enqueue(request);
return output;
}

Note

  1. You need to replace the title with your app name or some title about the content you download
  2. You need to replace the description with your download description
  3. More important is you need to replace the url with your url of the file to be downloaded

So as per the above code destination location is set under download folder of your package name and you can find your downloaded file in that location.

How to notify the app or activity once download is completed

Different people will have different kinds of requirement. This step is for people who need to use the file as soon as the downloading is completed. All we need to do is to send a internal broadcast message to the activity once the download is finished which can be achieved by small set of following code

IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
 registerReceiver(downloadReceiver, filter);

So after adding the above code your DownloadData() function will look like the following code.

private long DownloadFile() {
 long output;
 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
 DownloadManager.Request request = new DownloadManager.Request(Uri.parse("url of the file needs to be downloaded"));
 request.setTitle("Your download title");
 request.setDescription("Your description");
 //Setting the location to which the file is to be downloaded
 request.setDestinationInExternalFilesDir(YourActivity.this, Environment.DIRECTORY_DOWNLOADS, "your-filename.ext");
 output = downloadManager.enqueue(request);
 IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
 registerReceiver(downloadReceiver, filter);
 return output;
 }

After that you need to initialize the broadcast receiver in your activity using the following code in which you can write the next task after the download is completed.

private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

@Override
public void onReceive(final Context context, Intent intent) {

//download is finished ...you can write the code for next task here

}
};

How to access the downloaded file

Now in this step we write some code of how to access the downloaded file . All you need to do is to just add the following code . You need to give the same location which you provided while downloading the file in the above location.

File file = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS + "your -file-name");

How to share the downloaded file

Now we have the downloaded file in defined location in the code. But it will be very difficult to go there in file manager and search for a particular file. So for making things easier we will have a share button in which they can just share it will email watsap or any social media he want which allows sharing files. What you need to do is to implement the following function and call it inside the button onclick.

private void ShareFile() { 
File exportDir = new File("Your file path"); 
String fileName = "your file name"; 
File sharingGifFile = new File(exportDir, fileName); 
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); 
shareIntent.setType("application/csv"); 
Uri uri = Uri.fromFile(sharingGifFile); 
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share image")); 
}

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *