Downloading and Retrieving Files on SD card in Android using Android SDK in Eclipse

Posted By : Ankush Gulati | 31-Jan-2013

Android SD Card SDK Eclipse

Each android device supports external storage (SD card) which can be used directly by user to save multimedia content as well as by an app to save it's data. Since the Internal storage of a device is very limited so it becomes a necessity for an app to transfer the large files to SD card. 

Downloading Files in Android:

In Android version 2.3 Gingerbread (API level 9), a new service was added to android OS "DownloadManager" specially for the purpose of downloading files throughout HTTP requests. It automatically manages the Progress bar in Notification, large sized Files, Retry Download if fail or even after the device reboots. So, currently it's the best solution for downloading files. Below are the steps to create a simple application for testing purpose:

1. Create a new Android project in Eclipse.

2. Select Blank Activity.

3. In Activity_main.xml file, Place the below code.

  a.) One button to start downloading a file throughout internet.

  b.) Another button to Generate the list of files present in app directory.

  c.) Edit Text to display the list of files in app directory.

 

<RelativeLayout 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=".MainActivity" >
    <EditText
        android:id="@+id/listOfFiles"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="22dp"
        android:ems="10"
        android:inputType="textMultiLine" >
        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/getListOfFilesBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/listOfFiles"
        android:layout_marginTop="17dp"
        android:text="Get the list" />
    <Button
        android:id="@+id/fileDownloadBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/getListFiles"
        android:layout_marginTop="15dp"
        android:text="Download sample file" />
</RelativeLayout>

4. In your MainActivity.java file, paste the below code in OnCreate method of Activity

                
	Button fileDwnloadBtn=(Button)findViewById(R.id.fileDownloadBtn);
		fileDwnloadBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Boolean result=isDownloadManagerAvailable(getApplicationContext());
				if (result)
					downloadFile();
			}
		});

        

5. Paste the below two functions in same MainActivity class.

        @SuppressLint("NewApi")
	public void downloadFile(){
		String DownloadUrl = "Paste Url to download a pdf file here…";
		DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
		request.setDescription("sample pdf file for testing");   //appears the same in Notification bar while downloading
		request.setTitle("Sample.pdf");					
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
		    request.allowScanningByMediaScanner();
		    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		}
		request.setDestinationInExternalFilesDir(getApplicationContext(),null, "sample.pdf");

		// get download service and enqueue file
		DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
		manager.enqueue(request);
	}

	public static boolean isDownloadManagerAvailable(Context context) {
	    try {
	        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) {
	            return false;
	        }
	        Intent intent = new Intent(Intent.ACTION_MAIN);
	        intent.addCategory(Intent.CATEGORY_LAUNCHER);
	        intent.setClassName("com.android.providers.downloads.ui","com.android.providers.downloads.ui.DownloadList");
	        List <resolveinfo> list = context.getPackageManager().queryIntentActivities(intent,
	                PackageManager.MATCH_DEFAULT_ONLY);
	        return list.size() > 0;
	    } catch (Exception e) {
	        return false;
	    }
	}
      

 

a) isDownloadManagerAvailable Function queries and returns a boolean indicating whether the Download Manager Service for device's OS version or not (not available in Android version less than 2.3).

b) IF the above function returns TRUE, only then we can use the downloadFile method.

c) downloadFile function makes use of the DownloadManager manager to enqueue the download request and the process starts.

d) Notice this line:

             request.setDestinationInExternalFilesDir(getApplicationContext(),null, "sample.pdf");   
        

It simply places the file "sample.pdf" in your "/sdcard/Android/data/Your_Projects_PackageName/files/" directory.This directory is private to your app only. It will create this directory if doesn't exist already.

e) If You want the downloaded file to go to the default "Downloads" directory of SD card, replace the above line with below line:

            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "sample.pdf"); 
        

It's a public directory.

6. Now, Lastly, define the below two permissions in your AndroidManifest.xml file:

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

7. Now, Either create Emulator with SD card or test it on device. After giving proper download URL and Clicking on "Download File" button, downloading will start and you can see the progress in Notification bar like screenshot below.

 

Retrieving Files from SD card:

1. There are several ways to retrieve the list of files present in a particular directory of SD card. We'll be using the simplest approach.

2. Place the below code in your MainActivity.java file's OnCreate method of main activity:

		EditText listOfFiles=(EditText) findViewById(R.id.listOfFiles);
		Button getListBtn=(Button)findViewById(R.id.getListOfFilesBtn);
		
		getListBtn.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if (Environment.MEDIA_MOUNTED.equals(state)) {
				    // We can read and write the media
				    Toast.makeText(getApplicationContext(), "Media Mounted status: true", 5000).show();	    
				    try
				    {
				        File mfile=new File("/sdcard/Android/data/Your_Projects_PackageName/files/");
						File[] list=mfile.listFiles();
						if (list.length==0)
							listOfFiles.setText("Folder is empty");
						else
						{
							for(int i=0;i < list.length;i++)
								listOfFiles.setText("\n"+list[i].getName());
						}
				    }
				    catch(Exception e)
				    {
				    	Toast.makeText(getApplicationContext(), "Exception: Folder not created yet", 5000).show();
				    }
					
				} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
				    Toast.makeText(getApplicationContext(), "Media Mounted status: Read only access", 5000).show();
				} else {
				    Toast.makeText(getApplicationContext(), "Media Mounted status: Error occured", 5000).show();
				}
			}
		});

3. The Above code simply generates the list of files present in app's data folder and displays the list in Edit Text. (if there is no permission or access error).

 

Hope it helps  :)

Ankush Gulati

[email protected]

About Author

Author Image
Ankush Gulati

Request for Proposal

Name is required

Comment is required

Sending message..