編輯:關於 Android 程式設計
Android 強制採單線程模型,有兩條鐵則:不要阻塞 UI 線程;只能從 UI 線程存取 Android UI 工具包。UI 操作本身並非線程安全,因此背景運算與介面更新必須妥善分工。
App 啟動時,系統會同時起一條主線程,負責處理按鍵、觸控、繪圖等事件並分派給對應元件,因此主線程又稱 UI 線程。若在此做網路請求或大量計算,畫面就會卡住甚至 ANR。
Handler:為每個任務建立一條新線程,完成後透過 Handler 向 UI 線程送訊息以更新介面。彈性最高,但樣板程式碼多。
AsyncTask:把建立非同步任務的過程封裝起來,不必自己寫線程與 Handler,就能完成同樣的事。
public abstract class AsyncTask<Params, Progress, Result>
Params 是啟動任務時傳入的輸入參數型別;Progress 是背景任務執行期間回報的進度型別;Result 是背景運算的結果型別。範例中若為 AsyncTask<String, Integer, String>,代表傳入網址字串、以整數回報百分比、最後回傳網頁內容字串。
execute(Params... params):由呼叫端觸發,開始執行非同步任務。
onPreExecute():在 execute 之後立刻執行,跑在 UI 線程,常用於顯示進度條、禁用按鈕等前置狀態。
doInBackground(Params... params):在 onPreExecute 之後執行,跑在工作線程,是真正做耗時工作的所在。執行中可呼叫 publishProgress() 發布進度,並以 isCancelled() 檢查是否已被取消。
onProgressUpdate(Progress... values):在 publishProgress 被呼叫時觸發,跑在 UI 線程,可直接更新進度元件。
onPostExecute(Result result):背景工作結束後觸發,接收 doInBackground 的回傳值,跑在 UI 線程,用來把結果呈現在畫面上。
public class TestAsyncTask extends AsyncTask<String, Integer, String> {
static final String TAG = "testAsyncTask";
AsyncTaskCallback cb = null;
public static final int PRE_EVENT = 1;
public static final int POST_EVENT = 2;
public static final int CACEL_EVENT = 3;
public static interface AsyncTaskCallback {
void onAsyncResult(int e, String s); // 顯示結果
void onAsyncProcess(Integer pi); // 顯示進度
}
public TestAsyncTask(Context c, AsyncTaskCallback cb) {
this.cb = cb;
}
@Override
protected void onPreExecute() {
cb.onAsyncResult(PRE_EVENT, "loading...");
}
@Override
protected void onPostExecute(String result) {
cb.onAsyncResult(POST_EVENT, result);
}
@Override
protected void onCancelled() {
cb.onAsyncResult(CACEL_EVENT, "cancle loading");
}
@Override
protected void onProgressUpdate(Integer... values) {
cb.onAsyncProcess(values[0]);
}
@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();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[512];
int count = 0, length = -1;
while ((length = is.read(buf)) != -1) {
baos.write(buf, 0, length);
count += length;
// 發布進度,隨後 onProgressUpdate 會被呼叫
publishProgress((int) ((count / (float) total) * 100));
Thread.sleep(100); // 為了看清楚動畫,僅供示範
}
return new String(baos.toByteArray(), "utf-8");
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return null;
}
}
AsyncTaskCallback cb = new AsyncTaskCallback() {
@Override
public void onAsyncResult(int e, String s) {
Message msg = Message.obtain();
msg.what = 1;
msg.arg1 = e;
msg.obj = s;
testH.sendMessage(msg);
}
@Override
public void onAsyncProcess(Integer pi) {
Message msg = Message.obtain();
msg.what = 2;
msg.obj = pi;
testH.sendMessage(msg);
}
};
execute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// 每次都必須 new 一個新實例
task = new TestAsyncTask(MainActivity.this.getApplicationContext(), cb);
task.execute("https://www.example.com/");
execute.setEnabled(false);
cancel.setEnabled(true);
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
task.cancel(true); // 觸發 onCancelled()
}
});
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/execute"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="execute" />
<Button
android:id="@+id/cancel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="cancel" />
<ProgressBar
android:id="@+id/progress_bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:progress="0"
android:max="100" />
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
一個實例只能執行一次。重複呼叫 execute 會拋出 IllegalStateException,所以每次點擊都要 new 一個新的 AsyncTask。
預設是序列執行。從 Android 3.x(Honeycomb)起,同版本內多個 AsyncTask 會排隊依序執行,除非改用 executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params)。若想併發下載,必須明確指定。
與 Activity 生命週期脫鉤。若在背景任務執行中旋轉螢幕,Activity 重建後原任務的參照就斷了,結果會丟失。實務上應改用 ViewModel、Retained Fragment,或直接改用 Loaders。
已被取代。Android 11(API 30)起 AsyncTask 已被標記為 deprecated。新專案請改用 Kotlin 協程、WorkManager(適合可延後、需保證完成的工作)或 RxJava。理解 AsyncTask 的設計概念仍有價值,但 production 程式碼應選用現行方案。
Java 重難點面試題精選(一):集合、線程與異常機制
本文精選了一批 Java 面試中常見的重難點選擇題與程式閱讀題,涵蓋集合類的線程安全、值傳遞與引用傳遞、字串類別、異常體系、線程同步、Classloader 以及方法重寫
Android 刮刮樂效果實作:自定義擦除視圖
效果原理刮刮樂效果的本質,是在文字或圖案上覆蓋一層可擦除的遮罩。當使用者手指滑過時,遮罩被擦開,底下的內容逐漸顯現。自定義擦除元件可建立一個自訂 TextView,內部使
自定義 HorizontalScrollView 實作 QQ 側滑選單
QQ 風格側滑選單是常見的 Android 互動模式。要實作這類效果,可以自定義 HorizontalScrollView,讓選單在初始狀態下隱藏,並在使用者滑動時依手勢
Fresco 進階用法(二):進度條、縮放焦點、Controller 與漸進式 JPEG
上一篇談了 Fresco 的基本接入,這篇接著處理實務上一定會碰到的幾個進階需求:載入進度、縮放模式、Controller 相關的建構元件,以及漸進式 JPEG 與動圖播