new Thread(() -> {
try {
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10000);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
runOnUiThread(() -> imageView.setImageBitmap(bitmap));
}
} catch (IOException e) { e.printStackTrace(); }
}).start();
缺點:無快取、無生命週期感知、需手動處理 OOM、列表複用錯位。
| 庫 | 特色 | 適用場景 |
|---|---|---|
| Glide | Google 推薦、生命週期整合、GIF/WebP 支援、自動縮放 | 通用 App、列表圖片、中大型專案 |
| Coil | Kotlin 優先、協程ベース、輕量、Compose 整合佳 | Kotlin/Compose 專案、現代化技術棧 |
| Picasso | API 簡潔、Square 出品、維護模式(更新較慢) | 舊專案維護、簡單需求 |
| Fresco | Facebook 出品、共享記憶體、大圖分塊、WebP 動圖強 | 大圖瀏覽、社交餐飲類 App |
// build.gradle
implementation 'com.github.bumptech.glide:glide:4.16.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.16.0'
// 代碼
Glide.with(this)
.load(imageUrl)
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.centerCrop()
.into(imageView);
RandomAccessFile + Range 標頭實現斷點續傳。DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl));
request.setTitle("下載檔案");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "file.pdf");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
缺點:無法自定義進度 UI、不支援斷點續傳邏輯、Android 10+ 分區儲存限制多。
// 依賴
implementation "com.squareup.okhttp3:okhttp:4.12.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3"
// 下載協程
lifecycleScope.launch(Dispatchers.IO) {
val request = Request.Builder().url(fileUrl).build()
client.newCall(request).execute().use { response ->
val sink = File(outputPath).sink()
response.body?.source()?.use { source ->
source.copyTo(sink) // 自動緩衝、高效複製
}
}
withContext(Dispatchers.Main) { onDownloadComplete() }
}
AppGlideModule 或 Coil ImageLoader 擴展。HttpURLConnection + 線程池 + LruCache 手寫簡易快取。**圖片請直接用 Glide/Coil**,不要重複造輪子。檔案下載視業務複雜度選擇系統 DownloadManager(簡單)或 OkHttp 方案(完全控制)。所有網路操作**必須在子線程/協程**執行,並妥善處理生命週期、取消與錯誤重試。