編輯:關於 Android 開發
用手機時大概都遇到過這種情況:畫面先卡死幾秒,然後跳出「應用無響應,是否關閉」的對話框。這背後就是線程阻塞。
Android 的 UI 操作全部集中在主線程(UI 線程)上,如果我們在這條線程裡執行耗時操作——網絡請求、大文件讀寫、複雜計算——UI 線程就會被卡住,畫面無法刷新,觸摸事件無法響應。當阻塞超過約 5 秒(BroadcastReceiver 是 10 秒),系統就會判定 ANR(Application Not Responding)並彈出對話框。
最直覺的想法是把耗時操作丟到子線程去。先在佈局裡放一個 Button 和一個 TextView:
Button button = (Button) findViewById(R.id.button);
TextView textView = (TextView) findViewById(R.id.textView);
TranslateAnimation animation = new TranslateAnimation(0, 200, 0, 0);
animation.setRepeatCount(3);
animation.setDuration(2000);
textView.setAnimation(animation);
// 進入 app 時讓 textView 做移動動畫
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
new Thread(new Runnable() { // 創建一個新線程
@Override
public void run() {
try {
Thread.sleep(5000); // 模擬耗時操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
});
這樣寫確實解決了 ANR——但真實場景中耗時操作完成後往往還要更新界面。加兩句試試:
TextView view = (TextView) v;
view.setText("100");
程序立刻崩潰,報錯:
Only the original thread that created a view hierarchy can touch its views.
翻譯過來就是:只有創建 View 層級的那個線程才能修改它的 Views。
官方文檔把這件事講得很清楚:
There are simply two rules to Android's single thread model: 1. Do not block the UI thread 2. Do not access the Android UI toolkit from outside the UI thread
不要阻塞 UI 線程,也不要從 UI 線程之外操作 UI 組件。這兩條看似矛盾(既要移到子線程,又不能碰 UI),但官方提供了幾種把結果送回主線程的機制。
既然不能在別的線程直接改 UI,那就把操作「投遞」到 UI 線程去執行:
v.post(new Runnable() {
@Override
public void run() {
TextView view = (TextView) v;
view.setText("" + sun);
}
});
這種做法的缺點很明顯:
冗余,可讀性差,維護性差
每更新一次 UI 就要寫一段匿名內部類,邏輯被打散在各地,後續維護很痛苦。
AsyncTask 把「後台幹活」和「前台更新」封裝成了一對方法,結構清晰得多:
private class DownloadImageTask extends AsyncTask<String, Void, Integer> {
@Override
protected Integer doInBackground(String... urls) {
try {
Thread.sleep(5000); // 在子線程執行耗時操作
} catch (InterruptedException e) {
e.printStackTrace();
}
int sun = 100;
return sun;
}
@Override
protected void onPostExecute(Integer sum) {
button2.setText("" + sum); // 自動在主線程執行
}
}
在點擊事件裡調用:
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadImageTask().execute();
}
});
三個泛型參數的含義:Params(傳入參數類型)、Progress(進度值類型)、Result(返回結果類型)。四個可重寫的方法裡,doInBackground() 在子線程,其餘 onPreExecute()、onProgressUpdate()、onPostExecute() 都在主線程。
AsyncTask 從 API 30 起已被標記為廢棄。新項目裡的標準選擇是:
lifecycleScope / viewModelScope 和 withContext(Dispatchers.IO),代碼是同步風格但實際異步,還能自動跟隨生命週期取消。但無論用哪種方案,那兩條鐵律永遠不變:不要阻塞主線程,不要跨線程碰 UI。
MD5 加密實作教學:打造首次登入設定密碼與驗證流程
MD5 加密實作教學:打造首次登入設定密碼與驗證流程 很多 App 在第一次使用時會要求使用者設定密碼,之後再用密碼登入。本篇示範這樣一個流程:點擊按鈕時先判斷是否為首次
Android 實作「連點兩下返回鍵退出 App」功能
Android 實作「連點兩下返回鍵退出 App」功能 「連點兩下返回鍵才退出 App」是很常見的互動設計。實現它的大致思路是: 監聽返回鍵,比較兩次按壓的間隔,若低於
iOS 與 Android 網路抓包教學:tcpdump 入門與實務
iOS 與 Android 網路抓包教學:tcpdump 入門與實務 現代行動應用幾乎都會透過網路與伺服器互動。當功能出現異常時,抓包往往是最直接的診斷方式。若只需要快速
Kotlin 初探:在 Android 專案中整合 Kotlin
Kotlin 初探:在 Android 專案中整合 KotlinKotlin 是一套靜態型別的程式語言,可用於 JVM、Android 與瀏覽器等環境,並主打與 Java