Android download progress dialog

When you write an Android application to allow users to download files from a server, it is a good idea that they see a progress dialog. The progress dialog shows the percentage of download task completed. In this tip, I am going to show you how to write Java code to download a file from a URL. The file will be saved in your external card. The progress dialog displays while the file is being downloaded.

Now you need to create a new Android project. After that, you have to modify the activity_main.xml file to add one EditText and one Button. The EditText allows the user to input the file URL and the Button will be pushed to download the file.


<LinearLayout 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"
   android:orientation="vertical"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >
  <EditText
     android:id="@+id/txt_url"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:hint="Enter url here"
     android:inputType="text"
     android:layout_marginLeft="10dp"
     android:layout_marginRight="10dp"
      />
  
   <Button
      android:id="@+id/btlogin"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:onClick="downloadFile"
      android:layout_gravity="center"
      android:text="Download"
      android:layout_marginLeft="10dp"
      android:layout_marginRight="10dp"
       />  
      
</LinearLayout>


In the MainActivity class, code will be written to create a folder to store the downloaded file, and download the file. In the code below, createStoreDir() method is called to create a folder called edoc_download in the external storage of you device. The downloadFile method is called when the user pushes the Download button to download the file. If the output folder was created successfully, the download process will begin by calling the execute method of the BackTask class. Downloading the file from server can take much time so that this task must be placed in background process. One way to run a process in background is using the AsyncTask class. This class allows you to write code to perform tasks before the process start, in the progress of the process, and after process's completion. In this tip code, before the download starts, I show a progress dialog. While the process is running, code is written to read file content from the URL and write to the output path. And at the same time, update the percentage of download in the progress dialog. When the download task completes, the progress dialog closes.

  package com.example.andtip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

ProgressDialog pd;
Activity context;
String storeDir;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     context=this;
    
      }


   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.main, menu);
  
  

return true;
    
   }
  
  
   public void downloadFile(View view){
    storeDir=createStoreDir();
    if(storeDir!=null){
     try{

      EditText txturl=(EditText)findViewById(R.id.txt_url);
      String urlstring=txturl.getText().toString().trim();
      if(urlstring.length()>0){
      BackTask bt=new BackTask();
      bt.execute(urlstring);
}

}catch(Exception e){}
}
else{
   Toast.makeText(this, "Folder can't be create. Download failed.", Toast.LENGTH_LONG).show();
}
}
public String createStoreDir(){
   String storeDir=Environment.getExternalStorageDirectory()+"/edoc_download";
   File f=new File(storeDir);
   if(!f.exists())
      if(!f.mkdir()){
         Log.e("Error","Can't create edoc_download directory");
      return null;
}
else
  return storeDir;
else
  return storeDir;
   }


//background process to download the file from server
   private class BackTask extends AsyncTask<String,Integer,Void>{  
   protected void onPreExecute(){
       super.onPreExecute();
       pd = new ProgressDialog(context);
       pd.setTitle("Downloading the file to "+storeDir);
       pd.setMessage("Please wait.");
       pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
       pd.setMax(100);
       pd.setCancelable(true);
       pd.setIndeterminate(false);
       pd.show();
      
       }
  
  
  
       protected Void doInBackground(String...params){
         URL url;
         int count;
         try {
      

url = new URL(params[0]);
      String outpath="";
       try {
      
       File f=new File(storeDir);
       if(f.exists()){
       HttpURLConnection con=(HttpURLConnection)url.openConnection();
       InputStream is=con.getInputStream();
       String fullpath=url.getPath();
       String filename=fullpath.substring(fullpath.lastIndexOf('/')+1);
       outpath=storeDir+"/"+filename;
       FileOutputStream fos=new FileOutputStream(outpath);
       int lenghtOfFile = con.getContentLength();
       byte data[] = new byte[1024];   
           long total = 0;   
           while ((count = is.read(data)) != -1) {
             total += count;
             // publishing the progress
             publishProgress((int)((total*100)/lenghtOfFile));             
             // writing data to output file
             fos.write(data, 0, count);
           }
  
      is.close();
      fos.flush();
      fos.close();
      }
   else{
   Log.e("Error","Not found: "+storeDir);
  
   }

} catch (IOException e) {
e.printStackTrace();
}

////



} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      
   return null;
      
       }    
      
       protected void onProgressUpdate(Integer... progress) {
           //setting progress percentage
           pd.setProgress(progress[0]);
       }
      
       protected void onPostExecute(Void result){
      
       pd.dismiss();       
      
      
       }       
    
      
      }
}


Before running the project, you need to modify the AndroidManifest.xml file to allow the application to use internet and external storage by adding the following code (above the line: <application).

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


Android-download-progress-dialog

Posted by: Dara | post date: 05-20-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.