android之解析包時出現錯誤(二)
阿新 • • 發佈:2019-01-27
這次的原因不同,再記錄下
public class DownloadTask { /** * @param path下載地址 * @param filePath儲存路徑 * @param progressDialog進度條 * @return * @throws Exception */ 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();//獲得socket輸入流 File file = new File(filePath); FileOutputStream fos = new FileOutputStream(file);//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和伺服器資料夾裡的apk大小有些差別,我就嘗試把每次讀取的byte[]做小一點,也就是
byte[] buffer = new byte[1024];
這行程式碼,把1024改成了128,又改成了64,結果就沒問題了。
意外的收貨。你也遇到類似問題的話嘗試一下,good luck。
作者:jason0539