// 寫法一:直接傳遞
BitmapFactory.decodeStream(conn.getInputStream());
// 寫法二:存入變數
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
兩種寫法在語義上 **完全等價**,decodeStream 參數型別為 InputStream,無論是直接傳遞方法回傳值,還是先存變數再傳遞,位元碼行為一致。
InputStream is,區域變數 InputStream is = ... 會遮蔽成員,導致後續邏輯使用錯誤的串流。IOException 的上下文中,編譯錯誤;寫法二若包在 try-catch 中則通過編譯。try {
InputStream is = conn.getInputStream();
if (is == null) { Log.e("TAG", "InputStream is null"); return; }
bitmap = BitmapFactory.decodeStream(is);
if (bitmap == null) Log.w("TAG", "decodeStream returned null");
} catch (IOException e) {
Log.e("TAG", "decodeStream failed", e);
} finally {
try { if (is != null) is.close(); } catch (IOException ignored) {}
}
finally 關閉串流。BitmapFactory.Options 設定 inSampleSize 避免 OOM。