0
這是我的第一篇文章 - 所以我希望在代碼格式方面做得很好。api level 8 HttpURLConnection
也許你可以幫我以下的問題:
隨着上述API級10,我所有的HttpURLConnections工作正常,但我嘗試的API級別8部分(有時是大多數)下載文件(txt,html ...)的內容失敗。
我只是在服務器返回響應代碼「-1」時重複下載工作。這不是很令人滿意,但它起作用(或多或少) - 但我想這只是因爲我收到的內容很短(最多100個字符)這一事實 - 有時我認爲最後的一些字符被省略了,太。
但是現在我試圖實現一個更新程序(下載並安裝一個apk文件),其中大部分時間都失敗了,因爲apk文件是碎片的(我猜),所以在嘗試時出現「分析錯誤」安裝該文件。
我在做什麼錯?
謝謝你的幫助(如果你比我好,請保持友好的氣氛g)!
這裏是我的更新程序的代碼( - 正如你所看到的 - 沒有重複的機制如上所述):
String download_url = "http://url/";
String download_file = "name.apk";
//Local
String update_file = download_file;
File update_file_stream = context.getFileStreamPath(update_file);
//Connect
URL url = new URL(download_url + download_file);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
//Delete local File?
if(update_file_stream.exists()){
update_file_stream.delete();
}
//Download File
FileOutputStream fos = context.openFileOutput(update_file, Context.MODE_WORLD_READABLE);
InputStream is = c.getInputStream();
byte[] buffer = new byte[4096];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
//Install
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(update_file_stream), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
嗨...謝謝你的回答!我知道這個問題,但是所有的網絡活動都在「protected Void doInBackground(String ... arg0){}」或者「新的AsyncTask(){}」中執行。所以這似乎不會導致問題。 –
2013-02-24 12:55:32