首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 圖片與檔案下載全方案:原生 HttpURLConnection、ImageLoader、Glide、Volley、Coil 對比

     編輯:程式設計疑難解答

圖片下載三大流派

1. 原生 HttpURLConnection(教學/極輕量專案)

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、列表複用錯位。

2. 成熟圖片載入庫(生產首選)

庫特色適用場景
GlideGoogle 推薦、生命週期整合、GIF/WebP 支援、自動縮放通用 App、列表圖片、中大型專案
CoilKotlin 優先、協程ベース、輕量、Compose 整合佳Kotlin/Compose 專案、現代化技術棧
PicassoAPI 簡潔、Square 出品、維護模式(更新較慢)舊專案維護、簡單需求
FrescoFacebook 出品、共享記憶體、大圖分塊、WebP 動圖強大圖瀏覽、社交餐飲類 App

Glide 使用範例

// 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);

檔案下載方案

1. 原生 + Foreground Service(大檔、需進度條、斷點續傳)

  • 使用 RandomAccessFile + Range 標頭實現斷點續傳。
  • 前台服務顯示通知進度,防止系統殺死進程。
  • 參考 Downloader、DownloadManagerPro 成熟庫。

2. DownloadManager(系統級、簡單檔案)

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+ 分區儲存限制多。

3. OkHttp + 協程(現代化、全控制)

// 依賴
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() }
}

選型建議決策樹

  1. 只是顯示圖片 → Glide / Coil 一行代碼搞定。
  2. 需自定義圖片處理(濾鏡、裁剪、轉碼) → Glide AppGlideModule 或 Coil ImageLoader 擴展。
  3. 下載 PDF/APK/大檔案、需進度條、斷點續傳 → OkHttp + 協程 + Foreground Service 或成熟下載庫。
  4. 極簡專案、不想加依賴 → 原生 HttpURLConnection + 線程池 + LruCache 手寫簡易快取。

總結

**圖片請直接用 Glide/Coil**,不要重複造輪子。檔案下載視業務複雜度選擇系統 DownloadManager(簡單)或 OkHttp 方案(完全控制)。所有網路操作**必須在子線程/協程**執行,並妥善處理生命週期、取消與錯誤重試。

  1. 上一篇文章:
  2. 下一篇文章: