Follow these steps:
1) Declare a file name
String fileName; //for image fileName = "matchfine1.png"; //for pdf fileName = "samplepdf.pdf";
2) A method call to invoke the boot process.
startDownload(fileName);
3) Define the startDownload method:
//for download file start private void startDownload(String filename) { String filedowname = filename; //for image String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"; //for pdf String url = "http://people.opera.com/howcome/2005/ala/sample.pdf"; new DownloadFileAsync().execute(url,filedowname); }
4) To increase download speed Bar:
@Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Downloading file.."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setCancelable(false); mProgressDialog.show(); return mProgressDialog; default: return null; } }
5) Define a boot process that extends AsyncTask
class DownloadFileAsync extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override protected String doInBackground(final String... aurl) { try { File root = android.os.Environment.getExternalStorageDirectory(); File dir = new File (root.getAbsolutePath() + "/Your_file_save_path/"); if(dir.exists()==false) { dir.mkdirs(); } URL url = new URL(aurl[0]); String filename = aurl[1]; URLConnection conexion = url.openConnection(); conexion.connect(); int lenghtOfFile = conexion.getContentLength(); Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(dir+"/"+filename); byte data[] = new byte[1024]; long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; publishProgress(""+(int)((total*100)/lenghtOfFile)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) {} return null; } protected void onProgressUpdate(String... progress) { Log.d("ANDRO_ASYNC", progress[0]); mProgressDialog.setProgress(Integer.parseInt(progress[0])); } @Override protected void onPostExecute(String unused) { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); } }
6) Replace "Your_file_save_path" with your path to the file in the directory. and then download and check in the indicated location.
source share