Download a file using Async Task

Sunday 9 September 2012 1 comments
From the initial days of Android Application development, It recommends not to use Threads in the Main Thread or Class. But from ICS, it strictly says not to use Thread in main class and if do so, it will throw ' NetworkOnMainThreadException ' . So its wise to use Async task in all network operations.


Here I will show you a quick demo of how to download a Pdf file and saving that in the Downloads folder of your SD card. Will also open the file after downloading.

As we all know AsyncTask class have 3 methods.

  1. onPreExecute()
  2. doInBackground(String... urls)
  3. onPostExecute(String result)
So in onPreExecute, We will configure where it should download the file. You can change the folder as you need.

In doInBackground, We will do the network operations. I'm showing the progress bar here is to prevent other events to happen until the downloaded file got downloaded and its opened. If you are downloading other files which don't want to open after downloading, you can skip the progress bar so that the downloading will happen in the background and you other operation will also happen Asynchronously. 

Finally after the file got downloaded, onPostExecute method will be called. Lets open the downloaded file inside this method.

Thus, a file got downloaded and its brought to foreground using Intent.ACTION_VIEW. To call this class, 
                 DownloadAndOpenPDF pdfFile = new DownloadAndOpenPDF(this,pdfUrl);
pdfFile.execute(new String[] { pdfUrl });

And, below is the class comprises of all three methods together.






1 comments:

Post a Comment

 

©Copyright 2011 Bleed in Android | TNB