Resume下载在Android中不工作

前端之家收集整理的这篇文章主要介绍了Resume下载在Android中不工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尽管在 Java应用程序中可以正常工作,但是在 Android中恢复下载的代码无法正常工作.在这里我试图下载一个zip文件,它将恢复下载,但最终的结果是无效的zip文件.
BufferedInputStream in = null;
        FileOutputStream fos = null;
        BufferedOutputStream bout=null;

        try {
            downloaded=0;
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if(ISSUE_DOWNLOAD_STATUS.intValue()==ECMConstant.ECM_DOWNLOADING){
                File file=new File(DESTINATION_PATH);
                if(file.exists()){
                    downloaded = (int) file.length();
                }
            }
            connection.setRequestProperty("Range","bytes=" + downloaded + "-");
            connection.connect();
            size=connection.getContentLength();
            Dialog.setMax(size);
             in = new BufferedInputStream(connection.getInputStream());
             fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
             bout = new BufferedOutputStream(fos,1024);
            byte[] data = new byte[1024];
            int x = 0;
            while ((x = in.read(data,1024)) >= 0) {
                bout.write(data,x);
                 downloaded += x;
                 System.out.println(downloaded);
                 onProgressUpdate((int)(downloaded*100/size));
            }

            succes=true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
@H_404_4@谢谢.

解决方法

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int buf = 1024;

if (ISSUE_DOWNLOAD_STATUS.intValue() == ECMConstant.ECM_DOWNLOADING) {
    File file = new File(DESTINATION_PATH);
    if (file.exists()) {
         downloaded = (int) file.length();
         connection.setRequestProperty("Range","bytes=" + file.length() + "-");
    }
} else {
    connection.setRequestProperty("Range","bytes=" + downloaded + "-");
}

connection.setDoInput(true);
connection.setDoOutput(true);

progressBar.setMax(connection.getContentLength());
in = new BufferedInputStream(connection.getInputStream());
fos = new FileOutputStream(DESTINATION_PATH,downloaded == 0 ? false : true);
bout = new BufferedOutputStream(fos,buf);
byte[] data = new byte[buf];

while ((int x = in.read(data,buf)) >= 0) {
    bout.write(data,x);
    downloaded += x;
    progressBar.setProgress(downloaded);
}
原文链接:https://www.f2er.com/android/311162.html

猜你在找的Android相关文章