Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 錯誤之「解析包時出現錯誤」(二)

編輯:關於 Android 程式設計

之所以是「二」,是因為之前已經遇到過一次了。這次的原因不同,因此再記錄一次,作為經驗累積。

先來看一個執行下載任務的類,它用來從伺服器下載更新用的 apk:

public class DownloadTask {
    public static File getFile(String path, String filePath, ProgressDialog progressDialog) throws Exception {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(2000);
        connection.setRequestMethod("GET");
        if (connection.getResponseCode() == 200) {
            int total = connection.getContentLength();
            progressDialog.setMax(total);
            InputStream is = connection.getInputStream();
            File file = new File(filePath);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len;
            int progress = 0;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer);
                progress += len;
                progressDialog.setProgress(progress);
            }
            fos.flush();
            is.close();
            fos.close();
            connection.disconnect();
            return file;
        }
        return null;
    }
}

問題描述

下載成功後,程式跳轉到安裝頁面,卻提示「解析包時出現錯誤」。這種錯誤著實令人頭疼——它與程式碼邏輯無關,讓人毫無頭緒。

排查過程

後來筆者發現有類似案例,但該討論串並沒有提供解決方案。對比之下發現,下載回來的 apk 與伺服器資料夾裡的原始 apk 大小有些差別,於是便嘗試把每次讀取的 byte[] 做小一點,也就是調整這行:

byte[] buffer = new byte[1024];

把 1024 先改成了 128,又改成了 64,結果問題就解決了。這是個意外的收穫——下載緩衝區過大導致檔案寫入時出現細微偏差,進而使得 apk 檔案損壞、無法解析。

如果你也遇到類似問題,不妨嘗試縮小緩衝區大小,祝你好運!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved