6
我試圖將外部mp3下載到內部存儲器中。但是,我嘗試下載的文件很大,所以我試圖以1MB塊的形式下載它們,以便在下載其餘文件時開始播放它們。這裏是我的代碼流:InputStream將不會關閉,或永遠需要
InputStream is = null;
OutputStream os = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
MyLog.d("Connection established");
byte[] buffer = new byte[8192];
is = new BufferedInputStream(response.getEntity().getContent(), buffer.length);
os = openFileOutput(filename, MODE_PRIVATE);
int size;
int totalSize = 0;
while ((size = is.read(buffer)) != -1 && totalSize < 1048576) {
os.write(buffer, 0, size);
totalSize += size;
}
MyLog.d("Finished downloading mix - " + totalSize + " bytes");
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (os != null) {
try {
os.flush();
os.close();
}
catch (IOException e) {
MyLog.e("Failed to close output stream.");
}
}
if (is != null) {
try {
is.close();
}
catch (IOException e) {
MyLog.e("Failed to close input stream.");
}
}
}
它下載文件,但是當它到達is.close()在finally語句,它掛起。如果我長時間等待真的它最終會關閉。它似乎仍在下載文件的其餘部分。我如何避免這種情況並立即關閉流?
完美。謝謝! – 2011-04-24 23:39:23
也爲我工作。奇怪的是,大多數Android實現不會掛起。到目前爲止,我只在Droid X2上看到過這個。我的DefaultHttpClient abort方法中缺少 – dhaag23 2011-11-02 01:18:53
,但是mHttpClient.getConnectionManager()。shutdown()效果很好。 – pvllnspk 2012-10-26 12:16:02