views:

750

answers:

1

I am trying to write a simple application that gets updated. For this I need a simple function that can download a file and show the current progress in a ProgressDialog. I know how to do the ProgressDialog, but I'm not sure how to display the current progress and how to download the file in the first place.

+6  A: 

The best approach to do this is by using the AsyncTask class, as it will allow you to execute some background process and update the UI at the same time (in your case, it's a progress bar).

This is an example code:

ProgressBar mProgressBar;
// as you said you know how to use mProgressBar
// I'm not going to explain how to initialize it, etc.
DownloadFile DownloadFile = new DownloadFile();
DownloadFile.execute(archivo);

private class DownloadFile extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... url) {
        int count;

        try {
            URL url = new URL(url[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();

            // this will be useful so that you can show a tipical 0-100% progress bar
            int lenghtOfFile = conexion.getContentLength();

            // downlod the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress(""+(int)total*100/lenghtOfFile);
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
        return null;
    }

    @Override
    public void onProgressUpdate(String... args){
        // here you will have to update the progressbar
        // with something like mProgressBar.setProgress(Float.parseFloat(args[0]))
    }
}

You will also want to override the onPostExecute method if you want to execute some code once the file has been downloaded completely.

Cristian