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="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnProgressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:text="@string/btn_title" />

</LinearLayout>

[pgsubscribe]
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.

AsyncTaskExample.java
Open AsyncTask.java 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 java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
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 = "http://programmerguru.com/android-tutorial/wp-content/uploads/2014/01/jai_ho.mp3";

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);
			// Show Download Music Button
			btnPlayMusic = (Button) findViewById(R.id.btnProgressBar);
			// 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
					btnPlayMusic.setEnabled(false);
					// 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
						playMusic();
					// 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
		@Override
		protected Dialog onCreateDialog(int id) {
			switch (id) {
			case progress_bar_type:
				prgDialog = new ProgressDialog(this);
				prgDialog.setMessage("Downloading Mp3 file. Please wait...");
				prgDialog.setIndeterminate(false);
				prgDialog.setMax(100);
				prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				prgDialog.setCancelable(false);
				prgDialog.show();
				return prgDialog;
			default:
				return null;
			}
		}

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

			// Show Progress bar before downloading Music
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// Shows Progress Bar Dialog and then call doInBackground method
				showDialog(progress_bar_type);
			}

			// Download Music File from Internet
			@Override
			protected String doInBackground(String... f_url) {
				int count;
				try {
					URL url = new URL(f_url[0]);
					URLConnection conection = url.openConnection();
					conection.connect();
					// 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 = 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 Music File
			protected void onProgressUpdate(String... progress) {
				// Set progress percentage
				prgDialog.setProgress(Integer.parseInt(progress[0]));
			}

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

		// Play Music
		protected void playMusic(){
			// Read Mp3 file present under SD card
			Uri myUri1 = Uri.parse("file:///sdcard/jai_ho.mp3");
			mPlayer  = new MediaPlayer();
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			try {
					mPlayer.setDataSource(getApplicationContext(), myUri1);
					mPlayer.prepare();
					// Start playing the Music file
					mPlayer.start();
					mPlayer.setOnCompletionListener(new OnCompletionListener() {
						public void onCompletion(MediaPlayer mp) {
							// TODO Auto-generated method stub
							// Once Music is completed playing, enable the button
							btnPlayMusic.setEnabled(true);
							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();
			}
		}
}

AsyncTaskExample.java – 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" />

[pglinkadssmall1]

Demo

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.

[pglinkadssmall]

I hope this post is most useful to you!! ๐Ÿ™‚

Keep us posted with your valuable comments below ๐Ÿ™‚

[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • It took some working through, but this tutorial illustrated the features that I need for my current project. Thank you very much.

  • smartmouse

    showDialog and dismissDialog methos are both deprecated. Can you post an updated version of your code using DialogFragment class with FragmentManager? Thank you in advance.

  • Sure will do that when I get time.

  • Harsh Bhakta

    Exactly what I was looking for my app, good job. Those who want to see what type stands for in AsyncTask , visit http://stackoverflow.com/questions/6053602/what-arguments-are-passed-into-asynctaskarg1-arg2-arg3 .

  • Oliver Evans

    I’m a little bit confused as to why you include file_url as an argument for DownloadMusicfromInternet.execute(). Why is this necessary and when is it used? Thanks!

  • Aitor Ramos Pajares

    how do i can this when I clicked a button?

  • You can discard the parameter.

  • Amit

    Tutorial Content is nice explanation is also good but code is not Viable easily Without Horizontal Scroll view .is is very bad thing .we are not able to see full code in single screen .this is very very bad thing

  • Amolak Hooda

    When used this url ( http://dl.dropbox.com/s/4bevvo73nsm92ii/Sweet_Thoughts_030_sec.mp3 ), it says IO error, can u please help it to resolve?

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

Shares