Hi guys! Today we are going to do a script that will show an Android progress bar while downloading a file. A progress bar looks good for the user to be notified about the progress of the download.
We will easily use a UI thread with Android AsyncTask. In other terms, we will use a subclass to handle our downloader thread.
DownloadFile.java
package com.example.downloadfile; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.widget.TextView; public class DownloadFile extends Activity { public static final String LOG_TAG = “Android Downloader by The Code Of A Ninja”; //initialize our progress dialog/bar private ProgressDialog mProgressDialog; public static final int DIALOG_DOWNLOAD_PROGRESS = 0; //initialize root directory File rootDir = Environment.getExternalStorageDirectory(); //defining file name and url public String fileName = “codeofaninja.jpg”; public String fileURL = “https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG”; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setting some display setContentView(R.layout.main); TextView tv = new TextView(this); tv.setText(“Android Download File With Progress Bar”); //making sure the download directory exists checkAndCreateDirectory(“/my_downloads”); //executing the asynctask new DownloadFileAsync().execute(fileURL); } //this is our download file asynctask class DownloadFileAsync extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected String doInBackground(String… aurl) { try { //connecting to url URL u = new URL(fileURL); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod(“GET”); c.setDoOutput(true); c.connect(); //lenghtOfFile is used for calculating download progress int lenghtOfFile = c.getContentLength(); //this is where the file will be seen after the download FileOutputStream f = new FileOutputStream(new File(rootDir + “/my_downloads/”, fileName)); //file input is from the url InputStream in = c.getInputStream(); //here’s the download code byte[] buffer = new byte[1024]; int len1 = 0; long total = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; //total = total + len1 publishProgress(“” + (int)((total*100)/lenghtOfFile)); f.write(buffer, 0, len1); } f.close(); } catch (Exception e) { Log.d(LOG_TAG, e.getMessage()); } return null; } protected void onProgressUpdate(String… progress) { Log.d(LOG_TAG,progress[0]); mProgressDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected void onPostExecute(String unused) { //dismiss the dialog after the file was downloaded dismissDialog(DIALOG_DOWNLOAD_PROGRESS); } } //function to verify if directory exists public void checkAndCreateDirectory(String dirName){ File new_dir = new File( rootDir + dirName ); if( !new_dir.exists() ){ new_dir.mkdirs(); } } //our progress bar settings @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_PROGRESS: //we set this to 0 mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(“Downloading file…”); mProgressDialog.setIndeterminate(false); mProgressDialog.setMax(100); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(true); mProgressDialog.show(); return mProgressDialog; default: return null; } } }
And for the AndroidManifest.xml, include the INTERNET and WRITE_EXTERNAL_STORAGE permissions.
<?xml version=“1.0″ encoding=“utf-8″?> <manifest xmlns:android=“http://schemas.android.com/apk/res/android” package=“com.example.downloadfile” android:versionCode=“1″ android:versionName=“1.0″> <uses-permission android:name=“android.permission.INTERNET” /> <uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” /> <uses-sdk android:minSdkVersion=“4″ /> <application android:icon=“@drawable/icon” android:label=“@string/app_name”> <activity android:name=“.DownloadFile” android:label=“@string/app_name”> <intent-filter> <action android:name=“android.intent.action.MAIN” /> <category android:name=“android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest>
Thanks for reading this Android Download File With Progress Bar Example!
18 responses to “Android Download File With Progress Bar Example”
Hi, Mike! I’m beginner in android. I pasted your code in eclipse and ran it. But the exception is always happened and LogCat shows me this message: D/Android Downloader by The Code Of A Ninja(27306): /mnt/sdcard/my_downloads/codeofaninja.jpg: open failed: EACCES (Permission denied)
Please help me!)
hi, very tnx but i dont know how to set image in object ImageView after download?
please, help me!
my Email: Star.Night2007@gmail.com
Hi ! here is a nice tutorial!
I almost use the same stuff to download an apk package from my server and then, after the dowload, install it via the default package manager.
The download is done inside the doInBackground method, but when I try (using the onPostExecute() method) to install the package downloded, the package manager returns “parse error, there was a problem parsing the package”.
Is there something I’m missing here? Please help !
hi nice code but need URL in localhost …. ?
@anonymous – did you have WRITE permissions to your Android external storage in the manifest ?
Very nice, I searched for many samples, only yours works. Thx!
No downloading link here in this post, but thanks for a good post.
You’re welcome @disqus_hGtfEs04PW:disqus! Sorry this is a late reply, I’m receiving large amount of comments and I can’t see all of them. I think a download link is not needed for this one since only one java file and a single permission in the manifest file is included. But I’ll try to add it asap.
where is the showDialog() method?
Hi @anonymous, showDialog() is a built in method, but it’s deprecated since api level 13, see an alternative here http://stackoverflow.com/questions/10285047/showdialog-deprecated-whats-the-alternative
so it will automaticall call the progress dialog ??
Hi @marcjehuuy:disqus, it was called on the AsyncTask’s onPreExecute() method.
now this onCreate Dialog method depricated update your blog
Hello @arpitpatel009:disqus, thanks for the tip, we’ll update soon!
Your welcome
Hello I Need Help For Download Video IN Video Satus Application And This Download File Set In Progress Bar And Many More For Download Plzzzzzzz Help Me How To Do It………..
where is xml file code?
Please help me. The code works for single link…
I have a list view with base adapter… How can i download file that i click….
I am unable to use the string position in download async class…
Please reply me to nayasapnaa@gmail.com