我在使用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()获取。
有什么想法解决它吗?谢谢。
'FileOutputStream fileOutputStream = new FileOutputStream(aApkFile);'你在那里创建一个新文件。所以你会扔掉以前的部分下载。你没有提到那个不可分类的apk比原来的字节少。请通知我们。 – greenapps