Android的暂停和恢复下载文件到SD卡 [英] Android pause and resume downloading file to sdcard

查看:307
本文介绍了Android的暂停和恢复下载文件到SD卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

除了这没有为用户一个功能,暂停和恢复该文件。

我现在面临的问题是,我能够下载文件到SD卡,但是当尝试暂停和恢复它,它就会开始从一开始.......

下面是源......

 公共类DownloadWithProgressActivity延伸活动{    公共静态最终诠释DIALOG_DOWNLOAD_PROGRESS = 0;
    私人按钮startBtn,暂停按钮,resumeButton;
    私人进度条;
    URLConnection的conexion;
    OutputStream的输出;
    静态诠释计数= 0;    / **当第一次创建活动调用。 * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        startBtn =(按钮)findViewById(R.id.startBtn);
        暂停按钮=(按钮)findViewById(R.id.button1);
        resumeButton =(按钮)findViewById(R.id.button2);
        巴=(进度)findViewById(R.id.progressBar1);
        bar.setVisibility(ProgressBar.INVISIBLE);
        bar.setId(0);        startBtn.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                开始下载();
            }
        });
        pauseButton.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                尝试{
                    output.close();
                }赶上(IOException异常五){
                    // TODO自动生成catch块
                    e.printStackTrace();
                }
            }
        });
        resumeButton.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(查看为arg0){
                //没有得到什么写在这里
            }
        });
    }    私人无效startDownload(){
        字符串URL =htt​​p://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg;
        新DownloadFileAsync()执行(URL);
    }    类DownloadFileAsync扩展的AsyncTask<字符串,字符串,字符串> {        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            bar.setVisibility(ProgressBar.VISIBLE);        }        @覆盖
        保护字符串doInBackground(字符串... aurl){
            INT下载= 0;
            档案文件=新的文件(/ SD卡/ some_photo_from_gdansk_poland.jpg);
            网址URL = NULL;
            尝试{
                URL =新的URL(aurl [0]);
            }赶上(MalformedURLException的E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }
            尝试{
                conexion = url.openConnection();
                如果(file.exists()){
                    下载=(int)的file.length();
                    conexion.setRequestProperty(范围,字节=+(file.length())+ - );                }                其他{
                    conexion.setRequestProperty(范围,字节=+下载
                            + - );
                }
            }赶上(例外exception1){
            }
            conexion.setDoInput(真);
            conexion.setDoOutput(真);            的System.out.println(tryGetFileSize(URL));
            conexion.setRequestProperty(范围,字节=+数+ - );
            尝试{
                conexion.connect();
            }赶上(IOException异常E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }
            INT lenghtOfFile = conexion.getContentLength();
            Log.d(ANDRO_ASYNC,Lenght文件:+ lenghtOfFile);
            输入的InputStream = NULL;
            尝试{
                输入=新的BufferedInputStream(url.openStream());
            }赶上(IOException异常E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }
            尝试{
                输出=新的FileOutputStream(文件);
            }赶上(FileNotFoundException异常E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }
            字节的数据[] =新的字节[1024];
            总长= 0;
            尝试{
                而((计数= input.read(数据))!= - 1){
                    总+ =计数;
                    publishProgress(+(int)的((总* 100)/ lenghtOfFile));
                    output.write(数据0,计);
                }
            }赶上(IOException异常E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }
            尝试{
                output.flush();
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }
            尝试{
                output.close();
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }
            尝试{
                input.close();
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }            返回null;        }        保护无效onProgressUpdate(字符串...进度){
            Log.d(ANDRO_ASYNC进步[0]);
            bar.setProgress(的Integer.parseInt(进展[0]));
            的System.out.println(的Integer.parseInt(进展[0]));
        }        保护无效onPostExecute(字符串使用){
        }        INT tryGetFileSize(网址URL){
            HttpURLConnection的康恩= NULL;
            尝试{
                康恩=(HttpURLConnection类)url.openConnection();
                conn.setRequestMethod(HEAD);
                conn.getInputStream();
                返回conn.getContentLength();
            }赶上(IOException异常五){
                返回-1;
            } {最后
                conn.disconnect();
            }
        }    }
}


请帮忙.......

谢谢
尼基尔


解决方案

  connection.setRequestProperty(范围,字节=+ *** ***下载+ -  );

下载为全局变量,因为从这个位置开始下载

当你重启按钮preSS,检查此下载变量的值,不能为零所有的时间。

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

解决方案

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.

这篇关于Android的暂停和恢复下载文件到SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆