2017-05-05 64 views
-1

我在使用HttpUrlConnection下载apk时遇到问题。下载apk失败时,用httpUrlConnection继续下载

我开发了一个约30Mb的应用程序,并创建了一个管理器来检查最新版本并下载它。 因为它的大小,我检查下载的文件大小,并恢复下载,如果连接断开或应用程序被系统关闭。

问题是,如果整个下载过程中断一次,安装下载apk时发生解析错误。 这是错误消息:

解析错误:解析程序包时出现问题。

这里是我下载的代码:

private File downloadApk(File aApkFile, String aUrl, long aStartPosition, long aEndPosition) { 
    try { 
     URL url = new URL(aUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setConnectTimeout(5 * 1000); 
     conn.setReadTimeout(5 * 1000); 
     conn.setRequestMethod("GET"); 
     conn.setRequestProperty("Connection", "Keep-Alive"); 
     conn.setRequestProperty("Range", StringFormatter.format("bytes=%s-", aStartPosition)); 
     conn.connect(); 
     sendUpdateNotification(0, 100); // update notifaction info 
     InputStream inputStream = conn.getInputStream(); 
     FileOutputStream fileOutputStream = new FileOutputStream(aApkFile); 

     int currentPercent = 0; 
     long currentDownloadSize = aStartPosition; 
     byte readBuffer[] = new byte[1024 * 10]; 
     int byteReadSize = 0; 
     while (!((byteReadSize = inputStream.read(readBuffer)) <= 0)) { 
      fileOutputStream.write(readBuffer, 0, byteReadSize); 
      currentDownloadSize += byteReadSize; 
      int index = (int) (currentDownloadSize * 100/aEndPosition); 
      if (index != currentPercent) { 
       currentPercent = index; 
       sendUpdateNotification(currentPercent, 100); 
      } 
     } 
     fileOutputStream.close(); 
     inputStream.close(); 
     conn.disconnect(); 
     return aApkFile; 
    } catch (MalformedURLException aE) { 
     aE.printStackTrace(); 
     Log.e("Version", aE.getMessage()); 
    } catch (IOException aE) { 
     aE.printStackTrace(); 
     Log.e("Version", aE.getMessage()); 
    } 
    return null; 
} 

ApkFile是下载的文件,这将不会是空在这里。 StartPosition是apkfile的大小,并通过apkFile.length()获取。 Endposition是apk的整个大小,并通过conn.getContentLength()获取。

有什么想法解决它吗?谢谢。

+0

'FileOutputStream fileOutputStream = new FileOutputStream(aApkFile);'你在那里创建一个新文件。所以你会扔掉以前的部分下载。你没有提到那个不可分类的apk比原来的字节少。请通知我们。 – greenapps

回答

0

您与删除前部分文件:

FileOutputStream fileOutputStream = new FileOutputStream(aApkFile); 

更改为追加方式:原始和下载文件的

FileOutputStream fileOutputStream = new FileOutputStream(aApkFile, true); 

检查文件的大小。每个字节都很重要

+0

谢谢,它的工作原理。 – Cheng

+0

另外,我发现应该检查Connection.getResponseCode()。 在我的测试中,当我关闭wifi并在一段时间后打开它时,响应代码大部分是206.如果继续下载该响应代码,则apk文件大多会被破坏。所以我加了 'if(mConnection.getResponseCode()!= 200){ } }' 确保连接稳定。 – Cheng

+0

确实。基本的东西。 – greenapps