整體流程
- 用戶在
EditText 輸入關鍵字 → 發起搜索請求(HTTP GET/POST)。
- 服務端返回 JSON,包含圖片 URL 列表。
- 客戶端解析 JSON,將 URL 放入下載隊列。
- **線程池** 並發下載圖片,完成後通過 Handler 更新 UI。
- 圖片緩存至本地(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**。