AsyncTask<Params, Progress, Result> 是輕量級異步框架,內部封裝 Thread + Handler,適合**短時操作 (≤ 幾秒)**。長時間任務請用 ExecutorService、WorkManager 或 Coroutines。
execute() 傳入的參數類型 (如 URL 字串陣列)publishProgress() 發布的進度類型 (如 Integer 百分比)doInBackground() 返回的結果類型 (如 Bitmap)onPreExecute() → **主線程**,任務啟動前初始化 (顯示 ProgressDialog)。doInBackground(Params...) → **背景執行緒**,執行耗時操作,**不可操作 UI**,可呼叫 publishProgress()。onProgressUpdate(Progress...) → **主線程**,接收進度更新 UI (進度條)。onPostExecute(Result) → **主線程**,任務完成處理結果 (隱藏 Dialog、更新列表)。private static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> ivRef;
private final WeakReference<ProgressDialog> dialogRef;
DownloadImageTask(ImageView iv, ProgressDialog dialog) {
ivRef = new WeakReference<>(iv);
dialogRef = new WeakReference<>(dialog);
}
@Override protected void onPreExecute() {
dialogRef.get()?.show();
}
@Override protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
return BitmapFactory.decodeStream(is);
} catch (Exception e) {
Log.e("AsyncTask", "下載失敗", e);
return null;
}
}
@Override protected void onPostExecute(Bitmap bitmap) {
dialogRef.get()?.dismiss();
ImageView iv = ivRef.get();
if (iv != null && bitmap != null) iv.setImageBitmap(bitmap);
}
}
// 使用
new DownloadImageTask(imageView, progressDialog).execute(imageUrl);
private static class DownloadFileTask extends AsyncTask<String, Integer, File> {
private final WeakReference ctxRef;
private final WeakReference dialogRef;
DownloadFileTask(Context ctx, ProgressDialog dialog) {
ctxRef = new WeakReference<>(ctx);
dialogRef = new WeakReference<>(dialog);
}
@Override protected void onPreExecute() {
ProgressDialog d = dialogRef.get();
if (d != null) {
d.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
d.setMax(100);
d.show();
}
}
@Override protected File doInBackground(String... params) {
String urlStr = params[0];
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int total = conn.getContentLength();
InputStream is = conn.getInputStream();
File outFile = new File(ctxRef.get().getCacheDir(), "download.tmp");
FileOutputStream fos = new FileOutputStream(outFile);
byte[] buffer = new byte[4096];
int len, downloaded = 0;
while ((len = is.read(buffer)) != -1) {
if (isCancelled()) break; // 支援取消
fos.write(buffer, 0, len);
downloaded += len;
if (total > 0) publishProgress((int) (downloaded * 100L / total));
}
fos.close();
is.close();
return isCancelled() ? null : outFile;
} catch (Exception e) {
Log.e("AsyncTask", "下載異常", e);
return null;
}
}
@Override protected void onProgressUpdate(Integer... values) {
dialogRef.get()?.setProgress(values[0]);
}
@Override protected void onPostExecute(File file) {
dialogRef.get()?.dismiss();
if (file != null) {
Toast.makeText(ctxRef.get(), "下載完成:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
}
@Override protected void onCancelled(File file) {
dialogRef.get()?.dismiss();
Toast.makeText(ctxRef.get(), "已取消", Toast.LENGTH_SHORT).show();
}
}
task.cancel(true):true = 中斷執行緒 (Thread.interrupt()),false = 僅標記取消。doInBackground 定期檢查 isCancelled(),及時返回。onCancelled(Result),**不會**呼叫 onPostExecute。execute()。IllegalStateException。cancel() 避免洩漏 (持有 View/Context 參考)。ThreadPoolExecutor / WorkManager / Coroutines。| 方案 | 優點 | 缺點 |
|---|---|---|
| Kotlin Coroutines | 結構化並發、取消傳播、語法簡潔、生命週期感知 | 需學習協程概念 |
| RxJava | 強大操作符、背壓、跨平台 | 學習曲線陡、體積較大 |
| WorkManager | 延遲/周期性、保證執行、系統優化 | 不適用即時 UI 更新 |
| AsyncTask | API 簡單、無依賴 | **已棄用 (API 30)**、記憶體洩漏風險、執行緒池固定 |
💡 **Google 官方建議**:新代碼使用 Coroutines 或 RxJava,舊代碼漸進式遷移。