使用 HttpURLConnection + BitmapFactory.decodeStream() 從 URL 下載圖片,Toast 總顯示 "Image can't load",但網址在瀏覽器正常開啟。
Content-Encoding: gzip,getInputStream() 回傳壓縮資料流,BitmapFactory 無法直接解碼IOExceptionNetworkOnMainThreadException (API 11+)public Drawable getDrawableFromUrl(String urlString) {
try {
InputStream is = (InputStream) new URL(urlString).getContent(); // 自動處理 gzip
return Drawable.createFromStream(is, "src");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// 呼叫端 (需在背景執行緒)
new Thread(() -> {
Drawable d = getDrawableFromUrl("https://example.com/image.gif");
runOnUiThread(() -> {
if (d != null) imageView.setImageDrawable(d);
else Toast.makeText(this, "載入失敗", Toast.LENGTH_SHORT).show();
});
}).start();
實務專案請直接採用成熟圖片載入框架:
Glide.with(this).load(url).into(imageView);Picasso.get().load(url).into(imageView);imageView.load(url)框架內建快取、生命週期感知、錯誤重試、佔位圖等功能,避免重複造輪子。