0
我需要通過程序下載.apk文件,然後啓動其活動。 我使用的代碼如下Android下載的.apk文件損壞
private String downloadFile(String sourceURL, String destinationPath)
{
try {
URL url = new URL(sourceURL);
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(destinationPath);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) > 0) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
//此編輯:使文件RW,否則apk文件將不被安裝 調用Runtime.getRuntime()EXEC( 「搭配chmod 666」 +的DestinationPath) ;
message = "OK";
}
catch (MalformedURLException e) {
message = "Malformed URL error: " + e.getMessage();
}
catch (ProtocolException e) {
message = "Protocol exception error: " + e.getMessage();
}
catch (FileNotFoundException e) {
message = "File not found error: " + e.getMessage();
}
catch (IOException e) {
e.printStackTrace();
message = "Failed to download the file : " + e.getMessage();
}
return message;
}
我提到我先爲文本文件調用方法,然後再調用apk文件。因此,每次我在本地處理文件時,我都知道發生了什麼問題。通過這種方式,我知道文本文件已正確下載。但.apk文件已損壞。因爲我在本地開發,可以訪問DDMS和本地主機(IP:10.0.2.2),所以我可以堅信罪魁禍首就是上面的代碼。當我通過DDMS與原始.apk文件人爲地替換「下載」文件時,所有後續處理都是OK。另外,當我比較原始文件和下載的.apk文件時,我遇到了不同之處。 我在做什麼錯? 謝謝 PS:搜索,我意識到,雖然是一個流行的問題,但沒有一致的答案。就我而言,我將其確定爲純粹的下載方法問題。
服務器是否將APK作爲二進制文件發送? Content-Type標頭的值是什麼? – Rajesh
有趣。你建議setRequestProperty爲二進制?如果是這樣,什麼是正確的參數(因爲它似乎是相當面向應用程序的格式)。就像connection.setRequestProperty(「content-type」,「multipart/form-data」)? –
sourceURL的類型是什麼?它是一個HTTP請求?你從哪裏下載文件?您將不得不在服務器代碼中設置Content-Type標頭。 – Rajesh