Android暂停并恢复下载文件到SD卡

时间:2011-10-12 06:52:59

标签: android download sd-card resume-download

我正在制作一个应用程序,我需要从服务器下载文件并将其保存到Android设备的SD卡。

除此之外,用户还可以暂停和恢复文件。

我面临的问题是我能够将文件下载到SD卡但是当尝试暂停并恢复它时,它会从头开始.......

这是源......

public class DownloadWithProgressActivity extends Activity {

    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn, pauseButton, resumeButton;
    private ProgressBar bar;
    URLConnection conexion;
    OutputStream output;
    static int count = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        startBtn = (Button) findViewById(R.id.startBtn);
        pauseButton = (Button) findViewById(R.id.button1);
        resumeButton = (Button) findViewById(R.id.button2);
        bar = (ProgressBar) findViewById(R.id.progressBar1);
        bar.setVisibility(ProgressBar.INVISIBLE);
        bar.setId(0);

        startBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startDownload();
            }
        });
        pauseButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                try {
                    output.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        resumeButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //  not getting what to write here
            }
        });
    }

    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        new DownloadFileAsync().execute(url);
    }

    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            bar.setVisibility(ProgressBar.VISIBLE);

        }

        @Override
        protected String doInBackground(String... aurl) {
            int downloaded = 0;
            File file = new File("/sdcard/some_photo_from_gdansk_poland.jpg");
            URL url = null;
            try {
                url = new URL(aurl[0]);
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                conexion = url.openConnection();
                if (file.exists()) {
                    downloaded = (int) file.length();
                    conexion.setRequestProperty("Range", "bytes="+(file.length())+"-");

                }

                else {
                    conexion.setRequestProperty("Range", "bytes=" + downloaded
                            + "-");
                }
            } catch (Exception exception1) {
            }
            conexion.setDoInput(true);
            conexion.setDoOutput(true);

            System.out.println(tryGetFileSize(url));
            conexion.setRequestProperty("Range", "bytes=" + count + "-");
            try {
                conexion.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
            InputStream input = null;
            try {
                input = new BufferedInputStream(url.openStream());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                output = new FileOutputStream(file);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            byte data[] = new byte[1024];
            long total = 0;
            try {
                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                output.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                output.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                input.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;

        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC", progress[0]);
            bar.setProgress(Integer.parseInt(progress[0]));
            System.out.println(Integer.parseInt(progress[0]));
        }

        protected void onPostExecute(String unused) {
        }

        int tryGetFileSize(URL url) {
            HttpURLConnection conn = null;
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("HEAD");
                conn.getInputStream();
                return conn.getContentLength();
            } catch (IOException e) {
                return -1;
            } finally {
                conn.disconnect();
            }
        }

    }
}

请帮助.......

由于 NIKHIL

2 个答案:

答案 0 :(得分:2)

connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");

"downloaded"设为全局变量,因为下载从此位置开始。

当您按下重启按钮时,检查此下载变量的值,不能一直为零。

答案 1 :(得分:0)

此行返回错误的文件大小,我使用相同的代码在网上打开Zip文件:

int lenghtOfFile = conexion.getContentLength();

除关闭输出外,如何暂停下载?

pauseButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            try {
                output.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
resumeButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        //  not getting what to write here
    }
});