Thursday, October 21, 2010

Android/Java: Download a file from an URL to sdcard updating a ProgressBar/ProgressDialog

Here is a simple class for download management with ProgressDialog realtime updating

String path_to_local_file = "/mnt/sdcard/marco_bonifazi.txt";
String url = "http://www.bonifazi.eu/marco_bonifazi.txt";

DownloadManager downloader = new DownloadManager(this, url, path_to_local_file, dialog);

boolean res = downloader.checkInternetConnection();

if (!res ) {
    downloader.alertMissingConnection("No internet connections available");
} else {
    res = downloader.download();

    if (!res ) {
        downloader.alertMissingConnection("URL not available");
    } 
}


class DownloadManager extends AsyncTask{

    private URL url;
    private String filename;
    private ProgressDialog dialog;
    private URLConnection ucon;
    private Context context;
    
    public DownloadManager(Context context, String file_url, String filename, ProgressDialog dialog)  {
        this.context = context;
        this.dialog = dialog;

        try {
            this.url = new URL(file_url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        this.filename = filename;
    }
    
    public boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo() == null){
            return false;
        } else {
            return true;
        }
    }
    
    public void alertMissingConnection(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
        builder.setMessage(message)
        .setCancelable(false)
        .setPositiveButton("Ok", null);
        AlertDialog alert = builder.create();
        alert.show();
        return;
    }

    boolean download() {
        try {
            this.ucon = url.openConnection();
            this.ucon.connect();
            this.execute("");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected void onPreExecute() {
        this.dialog.setTitle("Downloading...");
        this.dialog.setIndeterminate(false);
        this.dialog.show();
    }
    @Override
    protected void onPostExecute(Integer result) {
        this.dialog.hide();
        this.alertMissingConnection("Download finished");
    }

    @Override
    public void onProgressUpdate(Integer... args) {
        this.dialog.setProgress(args[0].intValue());
    }

    @Override
    protected Integer doInBackground(String... params) {
        try {
            int n_bytes_packet = 0;
            int current_bytes_read = 0;
            int percent = 0;
            int n_total_bytes = this.ucon.getContentLength();

            BufferedInputStream ios = new BufferedInputStream(this.url.openStream());
            FileOutputStream fos = new FileOutputStream(new File(this.filename));
            byte data[] = new byte[256];

            while ((n_bytes_packet = ios.read(data)) != -1) {
                current_bytes_read += n_bytes_packet;
                percent =  current_bytes_read * 100 / n_total_bytes;
                fos.write(data, 0, n_bytes_packet);
                publishProgress(percent);
            }
            fos.flush();
            fos.close();
            ios.close();
            Log.d("fileManager", "Ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}



0 comments: