編輯:關於 Android 程式設計
AsyncTask 是 Android 早期為了解決「耗時操作不能跑在主執行緒」而提供的便捷方案。它讓背景運算與 UI 更新能用同一個類別寫完,不必自己管理執行緒與 Handler。本文把它的三個泛型參數、五個回呼方法,以及使用時的注意事項完整梳理一遍。
使用時必須繼承 AsyncTask 並指定三個泛型,例如 AsyncTask<Void, Integer, Void>:
execute() 時傳入的參數型別,也就是 doInBackground() 的參數型別。publishProgress() 與 onProgressUpdate() 的參數型別。doInBackground() 的回傳值型別,也就是 onPostExecute() 的參數型別。不需要用到某個型別時,直接填 Void 即可。
onPreExecute():在背景任務開始前於 UI 執行緒執行,適合做「顯示進度條」這類前置準備。doInBackground(Params...):必須實作,運行於背景執行緒,耗時操作寫在這裡。注意:不能在此方法中直接修改 UI。publishProgress(Progress...):在 doInBackground 中呼叫,把進度值送給 onProgressUpdate。此方法於 UI 執行緒執行。onProgressUpdate(Progress...):被 publishProgress 觸發,用來更新進度條等介面。onPostExecute(Result):doInBackground 執行完畢後於 UI 執行緒呼叫,用來顯示結果。onCancelled():任務被取消時呼叫,適合在此復原 UI 狀態。

1、建立 AsyncTask 的子類別,並為三個泛型參數指定型別,不需要的填 Void;
2、視需要覆寫 onPreExecute、doInBackground、onProgressUpdate、onPostExecute;
3、建立物件後呼叫 execute(params) 啟動。
package com.example.asynctestdemo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button bt_execute;
private Button bt_cancel;
private ProgressBar progressBar;
private TextView textView;
private MyTask myTask;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_execute = (Button) findViewById(R.id.bt_execute);
bt_cancel = (Button) findViewById(R.id.bt_cancel);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.text_view);
bt_execute.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// 建立非同步任務並啟動
myTask = new MyTask();
myTask.execute("https://www.baidu.com");
}
});
bt_cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myTask.cancel(true);
}
});
}
class MyTask extends AsyncTask<String, Integer, String> {
// 執行背景任務前,做一些 UI 準備
@Override
protected void onPreExecute() {
textView.setText("Loading......");
}
// 背景執行耗時操作,注意:不能在此修改 UI
@Override
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode()
== HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
long total = entity.getContentLength();
System.out.println(total);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int count = 0;
int length = -1;
while ((length = is.read(buf)) != -1) {
baos.write(buf, 0, length);
count += length;
// 公布進度,onProgressUpdate 隨後被觸發
publishProgress((int) (count * 100 / total));
// 為了明顯展示效果,每次暫停 0.5 秒
Thread.sleep(500);
}
return new String(baos.toByteArray(), "utf-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
// 更新進度資訊
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
textView.setText("Loading......" + values[0] + "%");
}
// 任務完成後更新 UI、顯示結果
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
// 任務被取消時復原 UI
@Override
protected void onCancelled() {
textView.setText("cancelled");
progressBar.setProgress(0);
}
}
}
1. 同一個 AsyncTask 只能執行一次。呼叫過 execute 之後,該物件就進入終態,再呼叫會拋 IllegalStateException。要重跑必須重新 new 一個。
2. 進度計算要小心除以零。範例原本寫成 count/length,若 length 為 -1(讀取結束)就會得到負數,且無法反映真實百分比。正確做法是拿 contentLength 當分母。
3. 記得在 onDestroy 中取消。Activity 旋轉或關閉後,背景任務若仍在跑,回呼時要操作已銷毀的介面,容易崩潰或洩漏。建議在 onDestroy 呼叫 myTask.cancel(true),並在 onPostExecute 前用 isCancelled() 判斷。
4. 它並不是真正的「新執行緒」保證。在 Android 3.2 之前,AsyncTask 是序列執行的(所有任務排隊);3.2 之後改為並行,但若要明確控制,可呼叫 executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params)。
5. 它已經被官方標記為不建議使用。從 API 30 起 AsyncTask 被 deprecated。新專案建議改用 Kotlin 協程、RxJava,或最簡單的 Thread + runOnUiThread/Handler 組合。理解 AsyncTask 的價值在於看懂舊專案,以及理解「背景運算 + UI 回呼」這個通用模式。
AsyncTask 的本質是「一條背景執行緒 + 一組往主執行緒拋訊息的捷徑」。它把 Handler 那套 template 包了起來,讓四五個回呼方法對應到不同階段。只要記住doInBackground 不能碰 UI、其餘回呼都在 UI 執行緒這條界線,就不會出錯。
開發 Android 地圖程式:Google Maps API v2 的 API Key 取得流程
要在 App 裡嵌入 Google 地圖,第一步永遠是拿到一組有效的 API Key。以下把整個流程拆成三個動作。 步驟一:找出你的 SHA1 憑證 開啟 Eclips
Android 網路編程入門(一):用 URLConnection 下載圖片
URL(Uniform Resource Locator,統一資源定位器)物件代表一個指向網際網路資源的指標。它由四個部分組成: protocol://host:por
自訂 View 實作隨機驗證碼:CheckView 與工具類拆分
對不少 Android 入門者來說,「自訂 View」四個字聽起來就有點可怕,但它其實是通往進階的必經之路。與其死讀理論,不如挑一個具體題目反覆練習。本文就以「隨機驗證碼
IntelliJ IDEA 與 Android Studio 上使用 Git 全流程圖文教程
由於 Android Studio 是基於 IntelliJ IDEA 開發而來的,所用的插件其實都源自 IDEA。IDEA 與 Android Studio 默認已經安