子線程下載圖片,InputStream in = conn.getInputStream() 直接傳給 BitmapFactory.decodeStream(in) 返回 null;不放在 run() 中則正常。
HttpURLConnection.getInputStream() 返回的流只能讀取一次,且必須在網絡線程中完整讀取。若在其他線程或多次讀取,流已關閉或位置錯誤。
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) baos.write(buffer, 0, len);
byte[] data = baos.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);