download with ProgressDialog - Android User Interface

Android examples for User Interface:ProgressDialog

Description

download with ProgressDialog

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ProgressDialog;

public class Main {

    public static File download(String filePath, String savePath,
            ProgressDialog pd) {/*from   w  w w  .  j a  v  a  2  s . c  om*/
        try {
            URL url = new URL(filePath);
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            conn.setConnectTimeout(5000);
            int code = conn.getResponseCode();
            if (code == 200) {
                File file = new File(savePath);
                FileOutputStream fos = new FileOutputStream(file);
                InputStream is = conn.getInputStream();

                int max = is.available();
                pd.setMax(max);
                int len = 0;
                byte[] buffer = new byte[1024];
                int total = 0;
                while ((len = is.read(buffer)) != -1) {

                    fos.write(buffer, 0, len);
                    total += len;
                    pd.setProgress(total);
                    Thread.sleep(30);
                }
                fos.flush();
                fos.close();
                is.close();

                return file;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}

Related Tutorials