Android Download Progress Bar

In this tutorial, you will learn how to implement a download progress bar in your Android application. A progress bar displays a bar to the user representing how far the operation has progressed. We will create a button and on button click will download an image file hosted in our server then stores it into the device internal storage. The download process will show a progress dialog with a bar stating the percentage of the image file being downloaded. So lets begin…

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project ProgressBarTutorial.

Application Name : ProgressBarTutorial

Project Name : ProgressBarTutorial

Package Name : com.androidbegin.progressbartutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.progressbartutorial;

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

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	// Declare variables
	ProgressDialog mProgressDialog;
	Button button;

	// Insert image URL
	String URL = "https://www.androidbegin.com/tutorial/testimage.png";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from activity_main.xml
		setContentView(R.layout.activity_main);

		// Locate a Button in your activity_main.xml layout
		button = (Button) findViewById(R.id.MyButton);

		// Capture Button clicks
		button.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// Execute DownloadFile AsyncTask
				new DownloadFile().execute(URL);
			}
		});

	}

	// DownloadFile AsyncTask
	private class DownloadFile extends AsyncTask<String, Integer, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create progress dialog
			mProgressDialog = new ProgressDialog(MainActivity.this);
			// Set your progress dialog Title
			mProgressDialog.setTitle("Progress Bar Tutorial");
			// Set your progress dialog Message
			mProgressDialog.setMessage("Downloading, Please Wait!");
			mProgressDialog.setIndeterminate(false);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			// Show progress dialog
			mProgressDialog.show();
		}

		@Override
		protected String doInBackground(String... Url) {
			try {
				URL url = new URL(Url[0]);
				URLConnection connection = url.openConnection();
				connection.connect();

				// Detect the file lenghth
				int fileLength = connection.getContentLength();

				// Locate storage location
				String filepath = Environment.getExternalStorageDirectory()
						.getPath();

				// Download the file
				InputStream input = new BufferedInputStream(url.openStream());

				// Save the downloaded file
				OutputStream output = new FileOutputStream(filepath + "/"
						+ "testimage.jpg");

				byte data[] = new byte[1024];
				long total = 0;
				int count;
				while ((count = input.read(data)) != -1) {
					total += count;
					// Publish the progress
					publishProgress((int) (total * 100 / fileLength));
					output.write(data, 0, count);
				}

				// Close connection
				output.flush();
				output.close();
				input.close();
			} catch (Exception e) {
				// Error Log
				Log.e("Error", e.getMessage());
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);
			// Update the progress dialog
			mProgressDialog.setProgress(progress[0]);
			// Dismiss the progress dialog
			//mProgressDialog.dismiss();
		}
	}
}

We have created a button and on button click will start an AsyncTask and download an image from a URL. The downloaded image will be stored in the internal storage.

In this tutorial, we’ve hosted our image file in our server. https://www.androidbegin.com/tutorial/testimage.png

Next, create a button in your MainActivity graphical layout. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file activity_main.xml and paste the following codes.

activity_main.xml

<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" >

    <Button
        android:id="@+id/MyButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/button" />

</RelativeLayout>

Next, change the application name and other texts. Open your strings.xml in your res > values folder and paste the following code.
strings.xml

<resources>

    <string name="app_name">ProgressBar Tutorial</string>
    <string name="menu_settings">Settings</string>
    <string name="button">Download Image</string>

</resources>

In your AndroidManifest.xml, we need to declare a permission to allow the application to write an external storage and connect to the Internet. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.progressbartutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output :

ProgressBar Tutorial ScreenShots

Source Code 

[purchase_link id=”7882″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

The perfect and objective tutorial! Thanks

Felipe

Android Download Progress Bar

thank u ...its working

vivek nayak

Android Download Progress Bar

its working for me, hvg only 1 problem suppose i want to save that image on my specified location how can i do that..... i tried doing this OutputStream output = new FileOutputStream(filepath + "/images/" +"testimage.jpg");

Tushar Salvi

Android Download Progress Bar

Hi Gurcan, are you are trying to cancel an AsyncTask? Follow this answer in stackoverflow http://stackoverflow.com/a/6053943/1196681 hope it helps. :)

AndroidBegin

Android Download Progress Bar