Sunday, November 24, 2013

Download file in Android application


You can download files in your android application without UI freeze.If your application has download file then you have to use threading or AsyncTask function.Which process in back end and without freeze the UI.

Here is the full tutorial,How to set download file function without freeze the UI.


  • First of all create new project named it 'Download file'.
  • Open activity_main.xml file and add below code in it.

activity_main.xml



<?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:text="Download File"
        android:layout_marginTop="50dip"/>

</LinearLayout>




  • Now Open MainActivity.java file and add below code.

MainActivity.java


public class MainActivity extends Activity {

Button btnShowProgress;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0; 
private static String file_url = "https://docs.google.com/uc?export=download&id=0B9w-wpPugvRfUUZDdWhtNU5qN1k";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
btnShowProgress.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
new DownloadFileFromURL().execute(file_url);
}
});
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}

@Override
protected String doInBackground(String... f_url) {
int count;
       try {
           URL url = new URL(f_url[0]);
           URLConnection conection = url.openConnection();
           conection.connect();
           // getting file length
           int lenghtOfFile = conection.getContentLength();

           // input stream to read file - with 8k buffer
           InputStream input = new BufferedInputStream(url.openStream(), 8192);
           
           // Output stream to write file
           OutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");

           byte data[] = new byte[1024];

           long total = 0;

           while ((count = input.read(data)) != -1) {
               total += count;
               // publishing the progress....
               // After this onProgressUpdate will be called
               publishProgress(""+(int)((total*100)/lenghtOfFile));
               
               // writing data to file
               output.write(data, 0, count);
           }

           // flushing output
           output.flush();
           
           // closing streams
           output.close();
           input.close();
           
       } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
       }
       
       return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";
}

}
}


  • Add Internet and Write Eternal Storage permissions in AndroidMenifest file.

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