Resume下载在Android中不工作

前端之家收集整理的这篇文章主要介绍了Resume下载在Android中不工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尽管在 Java应用程序中可以正常工作,但是在 Android中恢复下载的代码无法正常工作.在这里我试图下载一个zip文件,它将恢复下载,但最终的结果是无效的zip文件.
  1. BufferedInputStream in = null;
  2. FileOutputStream fos = null;
  3. BufferedOutputStream bout=null;
  4.  
  5. try {
  6. downloaded=0;
  7. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  8. if(ISSUE_DOWNLOAD_STATUS.intValue()==ECMConstant.ECM_DOWNLOADING){
  9. File file=new File(DESTINATION_PATH);
  10. if(file.exists()){
  11. downloaded = (int) file.length();
  12. }
  13. }
  14. connection.setRequestProperty("Range","bytes=" + downloaded + "-");
  15. connection.connect();
  16. size=connection.getContentLength();
  17. Dialog.setMax(size);
  18. in = new BufferedInputStream(connection.getInputStream());
  19. fos=(downloaded==0)? new FileOutputStream(DESTINATION_PATH): new FileOutputStream(DESTINATION_PATH,true);
  20. bout = new BufferedOutputStream(fos,1024);
  21. byte[] data = new byte[1024];
  22. int x = 0;
  23. while ((x = in.read(data,1024)) >= 0) {
  24. bout.write(data,x);
  25. downloaded += x;
  26. System.out.println(downloaded);
  27. onProgressUpdate((int)(downloaded*100/size));
  28. }
  29.  
  30. succes=true;
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. } finally {
  34. try {
  35. in.close();
  36. bout.close();
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40.  
  41. }

谢谢.

解决方法

  1. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  2. int buf = 1024;
  3.  
  4. if (ISSUE_DOWNLOAD_STATUS.intValue() == ECMConstant.ECM_DOWNLOADING) {
  5. File file = new File(DESTINATION_PATH);
  6. if (file.exists()) {
  7. downloaded = (int) file.length();
  8. connection.setRequestProperty("Range","bytes=" + file.length() + "-");
  9. }
  10. } else {
  11. connection.setRequestProperty("Range","bytes=" + downloaded + "-");
  12. }
  13.  
  14. connection.setDoInput(true);
  15. connection.setDoOutput(true);
  16.  
  17. progressBar.setMax(connection.getContentLength());
  18. in = new BufferedInputStream(connection.getInputStream());
  19. fos = new FileOutputStream(DESTINATION_PATH,downloaded == 0 ? false : true);
  20. bout = new BufferedOutputStream(fos,buf);
  21. byte[] data = new byte[buf];
  22.  
  23. while ((int x = in.read(data,buf)) >= 0) {
  24. bout.write(data,x);
  25. downloaded += x;
  26. progressBar.setProgress(downloaded);
  27. }

猜你在找的Android相关文章