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

发布于 2024-12-09 09:34:35 字数 5956 浏览 0 评论 0原文

我正在制作一个应用程序,其中我需要从服务器下载文件并将其保存到 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();
            }
        }

    }
}

请帮助。 ......

谢谢 尼基尔

I am making an application in which I need to download a file from server and save it to sd card of android device.

Apart of this there is a feature for the user to pause and resume the file.

The problem I am facing is that I am able to download file to sdcard but when try to pause and resume it, it gets starts from the beginning.......

Here is the source ......

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();
            }
        }

    }
}

Please help.......

Thanks
Nikhil

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千鲤 2024-12-16 09:34:35
connection.setRequestProperty("Range", "bytes=" + ***downloaded*** + "-");

“downloaded”设置为全局变量,因为下载从这个位置开始。

当您按下重新启动按钮时,请检查此下载变量的值,不得始终为零。

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

Make "downloaded" as global variable, because download start from this position.

when you press on restart button, check value of this downloaded variable,must not zero all time.

假面具 2024-12-16 09:34:35

此行返回错误的文件大小,我使用相同的代码在网上打开 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
    }
});

This line return a wrong file size, I used the same code to open a Zip file on the net :

int lenghtOfFile = conexion.getContentLength();

How can I pause download other than by closing the output?

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
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文