使用httpUrlConnection恢复下载时下载apk失败

时间:2017-05-05 01:41:04

标签: android download

我在使用HttpUrlConnection下载apk时遇到了问题。

我开发了一个大约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()获取。

有什么想法可以解决吗?感谢。

1 个答案:

答案 0 :(得分:0)

您正在删除以前的部分文件:

FileOutputStream fileOutputStream = new FileOutputStream(aApkFile);

更改为追加模式:

FileOutputStream fileOutputStream = new FileOutputStream(aApkFile, true);

检查原始文件和下载文件的文件大小。每个字节都很重要!

相关问题