Tuesday, May 31, 2011

AsyncTask download and updating the progress bar

I had a bit of trouble working out how to get the AsyncTask to update the progress bar on it's download; and examples were difficult to come by. As a result, I'm posting the AsyncTask subclass which will do the trick. Enjoy.


public class DownloadFilesTask extends AsyncTask {

private ProgressDialog dialog;
protected Context applicationContext;

// -- run intensive processes here
// -- notice that the datatype of the first param in the class
// definition
// -- matches the param passed to this method
// -- and that the datatype of the last param in the class definition
// -- matches the return type of this method
// -- The middle param matches the type of data passed to the process dialog.

@Override
protected String doInBackground(Void... params) {

downloadFromUrl();

// return Start.getTimeStampFromYahooService();
return "done";

}

@Override
protected void onPreExecute() {

this.dialog = new ProgressDialog(StartActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
dialog.setMax(numberOfBytesInFileToDownload) // note you will have to know this in advance
dialog.setMessage("Loading...");
dialog.show();

}

// -- called from the publish progress
// -- notice that the datatype of the second param gets passed to this
// method
@Override
protected void onProgressUpdate(Integer... values) {

dialog.setProgress(values[0]);
}

// -- called if the cancel button is pressed
@Override
protected void onCancelled() {
}

// -- called as soon as doInBackground method completes
// -- notice that the third param gets passed to this method

@Override
protected void onPostExecute(String result) {
this.dialog.dismiss();
}


public void downloadFromUrl() { // this is the downloader method
Log.d(TAG, "enter download from url");
try {

String PATH = Environment.getExternalStorageDirectory()
+ "/data/com.example.myapp/";

Log.v(TAG, "PATH: " + PATH);
URL url = new URL(
"http://www.mysite/xdroid/mySoundFile.mp3");

HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

File file = new File(PATH);
file.mkdirs();

String fileName = "mySoundFile.mp3";

File outputFile = new File(file, fileName);

long startTime = System.currentTimeMillis();
Log.d("DownloadTask", "download begining");
Log.d("DownloadTask", "download url:" + url);
Log.d("DownloadTask", "downloading file name:" + fileName);

/* Open a connection to that URL. */
FileOutputStream fos = new FileOutputStream(outputFile);

InputStream is = c.getInputStream();

byte[] buffer = new byte[1024];
int len1 = 0;
int cntr = 0;

while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
cntr++;
publishProgress(cntr * 1024);
}
fos.close();
is.close();

Log.d("DownloadTask",
"download ready in "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");

} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
Log.d(TAG, "exit download from url");

} // download from url

}

Note that the publishProgress pass the number of bytes downloaded, which will be used to display that metric vs. total file size, and calculate a percent as well.

No comments:

Post a Comment