Android DownloadManager example


In this Android tip, I am going to show you how to use DownloadManager class to download files from the internet. The DownloadManager is able to do HTTP long-run downloads in background. It takes care of HTTP interactions and retries after downloads failed or across connectivity changes and system reboots. The user can request to place a download file in a destination location, choose to display download progress in the notification bar, restrict the types of networks over which this download may proceed, and so on.
The download manager is a system service. To get an instance of the DownloadManager, you need to pass Context.Download_Server to the getSystemService() method of the current activity. A download request is made by creating an instance of the DownloadManager.Request class. Its constructor allows you to pass a file url to download. With the Request instance you can specify destination location on the external storage, choose to display download progress in the notification, set download title and description to display in the notification, restrict network types, and so on. The Request object will be passed to the enqueue() method of the DownloadManager instance to start the download task automatically when the DownloadManager is ready and connection is available.



To get the download status message when the download task complete, you need a BroadcastReceiver to receive the intent that matches ACTION_DOWNLOAD_COMPLETE. This intent is broadcast by the download manager.
The application that uses DownloadManager to download a file from the internet and save it on the external storage must add INTERNET and WRITE_EXTERNAL_STORAGE permissions to the AndroidManifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>


Now to provide you an example on DownloadManager, we are going to create a new Android project. Then, add an EditText, a Button, and a TextView to the activity_main.xml file as shown below.

<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"  
   tools:context="com.example.downmanager.MainActivity"
   android:orientation="vertical"
   >
   <EditText
     android:id="@+id/txturl"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:hint="Enter file url"
     />
   <Button
     android:id="@+id/btdownload"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:onClick="downloadFile"
     android:text="Download"
     />
   <TextView
     android:id="@+id/txtmessage"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:textColor="#ff1111"
     android:textSize="15sp"
     android:padding="15dp"
     />

</LinearLayout>


Here is the code written in the MainActivity class to use the DownloadManager class to download a file from a url input by the user in the EditText box.

 package com.example.downmanager;

import android.support.v7.app.ActionBarActivity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
//import android.app.DownloadManager.Request;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

DownloadManager dManager;
TextView tvMessage;
EditText urlInput;
long did;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get DownloadManager instance
dManager=(DownloadManager)this.getSystemService(Context.DOWNLOAD_SERVICE);
tvMessage=(TextView)findViewById(R.id.txtmessage);
urlInput=(EditText)findViewById(R.id.txturl);
}

public void downloadFile(View view){

String urlString=urlInput.getText().toString();
if(!urlString.equals("")){
try{
// Get file name from the url
String fileName=urlString.substring(urlString.lastIndexOf("/")+1);
// Create Download Request object
DownloadManager.Request request=new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
request.setDescription("Download "+fileName+" from "+ urlString);
// Set title
request.setTitle("DownloadManager");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://"+Environment.getExternalStorageDirectory()+"/"+fileName));
// Download the file if the Download manager is ready
did=dManager.enqueue(request);

}catch(Exception e){}

}


}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Query q = new Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if(cursor.moveToFirst()){
String message="";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(status==DownloadManager.STATUS_SUCCESSFUL){
message="Download successful";
}
else if(status==DownloadManager.STATUS_FAILED){
message="Download failed";
}
  tvMessage.setText(message);
}


}
};
protected void onResume(){
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter= new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}

}


Android-DownloadManager-example

Posted by: Dara | post date: 11-20-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.