Download Code

In this tutorial you will learn how to download something e.g song/image using Asynchronous task and display in android application.For this tutorial you must have knowledge of Asynchronous Task.

So,let’s just talk about all classes which we will use in this tutorial.

Asynchronous Task

URL

Uniform Resource Location.This class is basically used to identify the resource of your file defined by RFC 1738(Network Group).

URL Connecton

This class used for connection to a URL for a  file reading and writing.Instance of this class is not reusable.You have to create another instance for other url.

Input Stream

This class is used to read bytes from file system,network or anything else.

Buffered Input Stream

Enclose an existing InputStream and buffer the input.Because of this class direct interaction with inputstream is minimized.

Output Stream

This class is used to write bytes to a file system,network or anything else.

File Output Stream

This class is used to write bytes to a file.If file already exist it replace that file.
Ok let’s start by creating Android Application Project.After that go to your activity_main.xml file and use one Button.

asynchronous task

Now go to your MainActivity.java class.Create variable’s for.

  • Button
  • Progress Dialog(which will display the progress).
  • URL of a file.
  • ProgressBar type(we will use horizontal progress bar in this exercise).

Then refer id of a button and apply click event on that button.

After doing above steps your MainActivity.java class should look like this.

public class MainActivity extends Activity implements OnClickListener{

	Button down;   // download button variable
	ProgressDialog progressDialog;    // Progress Dialog variable
	public static final int progress_bar_type = 0;   // Progress Dialog type (0 - for Horizontal progress bar)
	private static String file_url = "http://androidcodec.com/sample/gunshot.mp3";     // file URL



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initialize();   // calling method to start UI components
	}
	public void initialize(){
		down = (Button) findViewById(R.id.downloadBtn);   // refering id of a button
		down.setOnClickListener(this);   // click event on button
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.downloadBtn:    // download button case 
			
			break;
		}
	}
}

Next create a Downloader class within the parent class.Extend Downloader class with Asynchronous Task and import four methods.Then your MainActivity.java class will look like this.

public class MainActivity extends Activity implements OnClickListener{

	Button down;   // download button variable
	ProgressDialog progressDialog;    // Progress Dialog variable
	public static final int progress_bar_type = 0;   // Progress Dialog type
	private static String file_url = "http://androidcodec.com/sample/gunshot.mp3";// file URL



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initialize();   // calling method to start UI components
	}
	public void initialize(){
		down = (Button) findViewById(R.id.downloadBtn);   // refering id of a button
		down.setOnClickListener(this);   // click event on button
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.downloadBtn:    // download button case 
			
			break;
		}
	}


	

	// our asynchronous task

	class Downloader extends AsyncTask<String, String, String>{

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
            
		}

		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			
         }

         
         protected void onProgressUpdate(String... progress) {
             
		}
	}
}


Then create a method for Progress bar Dialog.Call show method in onPreExecute(),dismiss method in onPostExecte() and set progress in onPressUpdate() method.After that MainActivity.java class will look like this.

public class MainActivity extends Activity implements OnClickListener{

	Button down;   // download button variable
	ProgressDialog progressDialog;    // Progress Dialog variable
	public static final int progress_bar_type = 0;   // Progress Dialog type (0 - for Horizontal progress bar)
	private static String file_url = "http://androidcodec.com/sample/gunshot.mp3";     // file URL



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initialize();   // calling method to start UI components
	}
	public void initialize(){
		down = (Button) findViewById(R.id.downloadBtn);   // refering id of a button
		down.setOnClickListener(this);   // click event on button
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.downloadBtn:    // download button case 
			
			break;
		}
	}


	// method of showing progress bar
	public Dialog onCreateDialog(int id){
		switch (id) {
		case progress_bar_type:
			progressDialog = new ProgressDialog(this);  
			progressDialog.setMessage("Downloading In Progess.Please wait...");  // setting message display
			progressDialog.setIndeterminate(false);                    
			progressDialog.setMax(100);                    // maximum length of progress bar
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);   // progress bar style type
			progressDialog.setCancelable(false);    // setting not cancelable while progress
			progressDialog.show();                // show method
			return progressDialog;
		default:
			return null;

		}
	}


	// our asynchronous task

	class Downloader extends AsyncTask<String, String, String>{

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showDialog(progress_bar_type);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			 // Dismiss the dialog of progress bar file was downloaded
            dismissDialog(progress_bar_type);
            Toast.makeText(getApplicationContext(), "Done! Check your Storage ", Toast.LENGTH_LONG).show();
            
		}

		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			
         }

         // While Downloading File
         protected void onProgressUpdate(String... progress) {
             // Set progress percentage
             progressDialog.setProgress(Integer.parseInt(progress[0]));
		}
	}
}

Now at last we will deal with background computation which is our main point.Everything will be instead Exceptions.Here are the steps.

  • First setting url of a file.
  • open url connection and connect using connect() method.
  • Calculate length of a file.
  • Read bytes of a file using buffer(8k) and pass to inputstream.
  • OuputStream will write that bytes in a file.
  • Loop for publishprogress and writing bytes to a file.
  • Flush output from buffer and close that stream.

After that go into case of button and set directory of storing downloaded file.That’s it.

Complete MainActivity.java.

package androidcodec.asynctask;

/*
 * 
 * All Rights Reserved By: Farhan Rasheed
 * 
 * */

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{

	Button down;   // download button variable
	ProgressDialog progressDialog;    // Progress Dialog variable
	public static final int progress_bar_type = 0;   // Progress Dialog type (0 - for Horizontal progress bar)
	private static String file_url = "http://androidcodec.com/sample/gunshot.mp3";     // file URL



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initialize();   // calling method to start UI components
	}
	public void initialize(){
		down = (Button) findViewById(R.id.downloadBtn);   // refering id of a button
		down.setOnClickListener(this);   // click event on button
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.downloadBtn:    // download button case 
			File file = new File(Environment.getExternalStorageDirectory().getPath()+"/gunshot.mp3");  // downloaded file path like music
			if(file.exists()){
				Toast.makeText(getApplicationContext(), "Already Downloaded", Toast.LENGTH_SHORT).show();  // display toast that file already exist

			}
			else{
				// calling AsyncTask to download file
				new Downloader().execute(file_url);
			}
			break;
		}
	}


	// method of showing progress bar
	public Dialog onCreateDialog(int id){
		switch (id) {
		case progress_bar_type:
			progressDialog = new ProgressDialog(this);  
			progressDialog.setMessage("Downloading In Progess.Please wait...");  // setting message display
			progressDialog.setIndeterminate(false);                    
			progressDialog.setMax(100);                    // maximum length of progress bar
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);   // progress bar style type
			progressDialog.setCancelable(false);    // setting not cancelable while progress
			progressDialog.show();                // show method
			return progressDialog;
		default:
			return null;

		}
	}


	// our asynchronous task

	class Downloader extends AsyncTask<String, String, String>{

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			showDialog(progress_bar_type);
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			 // Dismiss the dialog of progress bar file was downloaded
            dismissDialog(progress_bar_type);
            Toast.makeText(getApplicationContext(), "Done! Check your Storage ", Toast.LENGTH_LONG).show();
            
		}

		
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			 int count;
             try {
                 URL url = new URL(params[0]);
                 URLConnection conection = url.openConnection();
                 conection.connect();
                 // Get file length
                 int lenghtOfFile = conection.getContentLength();
                 // input stream to read file - with 8k buffer
                 InputStream input = new BufferedInputStream(url.openStream(),10*1024);
                 // Output stream to write file in phone directory
                 OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/jai_ho.mp3");
                 byte data[] = new byte[1024];
                 long total = 0;
                 while ((count = input.read(data)) != -1) {
                     total += count;
                     // Publish the progress which triggers onProgressUpdate method
                     publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                     // Write data to file
                     output.write(data, 0, count);
                 }
                 // Flush output
                 output.flush();
                 // Close streams
                 output.close();
                 input.close();
             } catch (Exception e) {
                 Log.e("Error: ", e.getMessage());
             }
             return null;
         }

         // While Downloading File
         protected void onProgressUpdate(String... progress) {
             // Set progress percentage
             progressDialog.setProgress(Integer.parseInt(progress[0]));
		}
	}
}


At last add permission for INTERNET AND WRITE EXTERNAL STORAGE.

asynchronous task

Now run your android application project your output should look like this after clicking download button.

asynchronous task

that’s it for this tutorial.I hope you get everything in good form.

Thanks.