Android AsyncTask Example

In this post, we are going to discuss about the usage of AsyncTask in Android applications with simple example. I have created simple example to demonstrate how AsyncTask can be used in Android applications.

Take a look at AsyncTask tutorial which will be helpful for you to understand the example with much ease.
Video Demo

Quick Links

Project Structure

Create layout XML

  • Create new android project [File >> New >> Android Application Project] with project name AsyncTaskExample
  • Choose Build SDK and minimum required SDK [I chose version 4.1 and 2.2]
  • Enter package name as ‘com.prgguru.example’
  • Click next and select BlankActivity
  • Click next and provide Activity name and Layout name as ‘AsyncTaskExample’ and ‘main’ respectively.

Code Listings

Open main.xml, now you can view the layout as either XML or in graphical view and just replace the XML with below one:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="@string/btn_title" />


We need to create two classes:

  1. AsyncTaskExample – UI Class which triggers Music download
  2. DownloadMusicfromInternet – Inner class inside AsyncTaskExample class which downloads Mp3 from Internet and plays it.
Open and replace it with below code. Each line is added with comment and I hope it is self understandable. If you still have any doubt/question, discuss it right away in the comment section.

package com.prgguru.example;


import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AsyncTaskExample extends Activity {
		// Button to download and play Music
		private Button btnPlayMusic;
		// Media Player Object
		private MediaPlayer mPlayer;
		// Progress Dialog Object
		private ProgressDialog prgDialog;
		// Progress Dialog type (0 - for Horizontal progress bar)
		public static final int progress_bar_type = 0;
		// Music resource URL
		private static String file_url = "";

		public void onCreate(Bundle savedInstanceState) {
			// Show Download Music Button
			btnPlayMusic = (Button) findViewById(;
			// Download Music Button click listener
			btnPlayMusic.setOnClickListener(new View.OnClickListener() {
				// When Download Music Button is clicked
				public void onClick(View v) {
					// Disable the button to avoid playing of song multiple times
					// Downloaded Music File path in SD Card
					File file = new File(Environment.getExternalStorageDirectory().getPath()+"/jai_ho.mp3");
					// Check if the Music file already exists
					if (file.exists()) {
						Toast.makeText(getApplicationContext(), "File already exist under SD card, playing Music", Toast.LENGTH_LONG).show();
						// Play Music
					// If the Music File doesn't exist in SD card (Not yet downloaded)
					} else {
						Toast.makeText(getApplicationContext(), "File doesn't exist under SD Card, downloading Mp3 from Internet", Toast.LENGTH_LONG).show();
						// Trigger Async Task (onPreExecute method)
						new DownloadMusicfromInternet().execute(file_url);

	    // Show Dialog Box with Progress bar
		protected Dialog onCreateDialog(int id) {
			switch (id) {
			case progress_bar_type:
				prgDialog = new ProgressDialog(this);
				prgDialog.setMessage("Downloading Mp3 file. Please wait...");
				return prgDialog;
				return null;

		// Async Task Class
		class DownloadMusicfromInternet extends AsyncTask<String, String, String> {

			// Show Progress bar before downloading Music
			protected void onPreExecute() {
				// Shows Progress Bar Dialog and then call doInBackground method

			// Download Music File from Internet
			protected String doInBackground(String... f_url) {
				int count;
				try {
					URL url = new URL(f_url[0]);
					URLConnection conection = url.openConnection();
					// Get Music 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 SD card
					OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/jai_ho.mp3");
					byte data[] = new byte[1024];
					long total = 0;
					while ((count = != -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
					// Close streams
				} catch (Exception e) {
					Log.e("Error: ", e.getMessage());
				return null;

			// While Downloading Music File
			protected void onProgressUpdate(String... progress) {
				// Set progress percentage

			// Once Music File is downloaded
			protected void onPostExecute(String file_url) {
				// Dismiss the dialog after the Music file was downloaded
				Toast.makeText(getApplicationContext(), "Download complete, playing Music", Toast.LENGTH_LONG).show();
				// Play the music

		// Play Music
		protected void playMusic(){
			// Read Mp3 file present under SD card
			Uri myUri1 = Uri.parse("file:///sdcard/jai_ho.mp3");
			mPlayer  = new MediaPlayer();
			try {
					mPlayer.setDataSource(getApplicationContext(), myUri1);
					// Start playing the Music file
					mPlayer.setOnCompletionListener(new OnCompletionListener() {
						public void onCompletion(MediaPlayer mp) {
							// TODO Auto-generated method stub
							// Once Music is completed playing, enable the button
							Toast.makeText(getApplicationContext(), "Music completed playing",Toast.LENGTH_LONG).show();
			} catch (IllegalArgumentException e) {
				Toast.makeText(getApplicationContext(), "You might not set the URI correctly!",	Toast.LENGTH_LONG).show();
			} catch (SecurityException e) {
				Toast.makeText(getApplicationContext(),	"URI cannot be accessed, permissed needed",	Toast.LENGTH_LONG).show();
			} catch (IllegalStateException e) {
				Toast.makeText(getApplicationContext(),	"Media Player is not in correct state",	Toast.LENGTH_LONG).show();
			} catch (IOException e) {
				Toast.makeText(getApplicationContext(),	"IO Error occured",	Toast.LENGTH_LONG).show();
} – Quick Explanation

  1. AsyncTaskExample > onCreate() – Triggers Downloading and playing of Music File
  2. AsyncTaskExample > onCreateDialog() – Shows Progress Bar Dialog when showDialog method is called in onPreExecute method
  3. AsyncTaskExample > DownloadMusicfromInternet > onPreExecute() – Executed when execute() method is called inside onCreate() (In short When AsyncTask is triggered).
  4. AsyncTaskExample > DownloadMusicfromInternet > doInBackground() – Executed when onPreExecute() completed executing. Downloading of Music file happens in this method which keeps updating the progress bar with progress of music file download by calling publishProgress() method. publishProgress() method calls onProgressUpdate() method where the progress bar’s progress is being updated.
  5. AsyncTaskExample > DownloadMusicfromInternet > onPostExecute() – Progress Bar Dialog is dismissed as the download of music file is completed and calls playMusic() method to play the Music file downloaded.

AndroidManifest.xml permission

Don’t forget to add write and internet permissions in AndroidManifest.xml:

    <!-- Permission: Allow application to connect to Internet -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Permission: Allow application to write to SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />



Let us test the application:

Right click on the project >> Run as >> Android application

You could see following screen:

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.


I hope this post is most useful to you!! 🙂

Keep us posted with your valuable comments below 🙂


Related Articles

Author: Udhay

Share This Post On
468 ad
Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest