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

Android 從服務器查詢並批量下載圖片:架構設計與線程池實現

     編輯:程式設計綜合問答

整體流程

  1. 用戶在 EditText 輸入關鍵字 → 發起搜索請求(HTTP GET/POST)。
  2. 服務端返回 JSON,包含圖片 URL 列表。
  3. 客戶端解析 JSON,將 URL 放入下載隊列。
  4. **線程池** 並發下載圖片,完成後通過 Handler 更新 UI。
  5. 圖片緩存至本地(SD 卡 / 內部存儲),列表展示縮略圖。

關鍵代碼片段

1. 搜索建議(AutoCompleteTextView)

AutoCompleteTextView actv = findViewById(R.id.search_box);
actv.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, historyList));
actv.setThreshold(1); // 輸入 1 字符提示

2. 異步下載線程池

ExecutorService executor = Executors.newFixedThreadPool(3); // 限制併發數
Handler mainHandler = new Handler(Looper.getMainLooper());

for (String url : imageUrls) {
    executor.submit(() -> {
        Bitmap bitmap = downloadBitmap(url);
        mainHandler.post(() -> {
            // 更新 UI:將 bitmap 設置到 ImageView 或保存文件
            imageView.setImageBitmap(bitmap);
        });
    });
}

private Bitmap downloadBitmap(String urlString) {
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(10000);
        return BitmapFactory.decodeStream(conn.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

優化建議

  • 使用成熟圖片加載庫:**Glide**、**Picasso**、**Coil (Kotlin)**,自動處理緩存、生命周期、併發、占位圖。
  • 大量圖片採用 **分頁加載**(Pagination / Load More)。
  • 下載服務前置:IntentService / WorkManager 後台下載,完成後發廣播通知 UI。
  • 網絡層統一用 **Retrofit + OkHttp** 或 **Ktor**。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved