有人可以告訴我這段代碼哪裏出錯了嗎?基本上我希望應用程序下載一個.png文件,將其顯示給用戶,並將其保存到SD卡以供將來參考。它似乎一切正常,直到while ((len = webstream.read(buffer)) > 0)
部分;因爲調試器沒有達到我放在這裏的斷點,我有一個空的.png文件的目錄。我在我的Manifest中聲明瞭WRITE_EXTERNAL_STORAGE
權限。SD卡寫入失敗?
protected class DownloadTask extends AsyncTask<String, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... string) {
Bitmap d = null;
try {
DefaultHttpClient dhc = new DefaultHttpClient();
HttpGet request = new HttpGet(HTTP_BASE + string[0] + ".png");
HttpResponse response = dhc.execute(request);
BufferedInputStream webstream = new BufferedInputStream(response.getEntity().getContent());
d = BitmapFactory.decodeStream(webstream);
writeToSd(string[0], webstream, d);
}
catch (Exception ex) { ex.printStackTrace(); }
return d;
}
private void writeToSd(String string, BufferedInputStream webstream, Bitmap d) {
try {
webstream.mark(3);
webstream.reset();
File f = new File(Environment.getExternalStorageDirectory() + SD_DIR);
f.mkdirs();
File f2 = new File(f, string + ".png");
f2.createNewFile();
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(f2));
int len;
byte[] buffer = new byte[1024];
while ((len = webstream.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
webstream.close();
//fos.flush();
fos.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
iv.setImageBitmap(result);
vs.setDisplayedChild(1);
}
}
};
是的,試過這個,它工作出色,謝謝! – 2010-10-02 12:55:06