Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Studio 學習隨筆:UI 線程阻塞與三種優化方案

編輯:關於 Android 開發

Android Studio 學習隨筆:UI 線程阻塞與三種優化方案

用手機時大概都遇到過這種情況:畫面先卡死幾秒,然後跳出「應用無響應,是否關閉」的對話框。這背後就是線程阻塞。

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。

Android 單線程模型的两條鐵律

官方文檔把這件事講得很清楚:

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),但官方提供了幾種把結果送回主線程的機制。

方案二:View.post()

既然不能在別的線程直接改 UI,那就把操作「投遞」到 UI 線程去執行:

v.post(new Runnable() {
    @Override
    public void run() {
        TextView view = (TextView) v;
        view.setText("" + sun);
    }
});

這種做法的缺點很明顯:

冗余,可讀性差,維護性差

每更新一次 UI 就要寫一段匿名內部類,邏輯被打散在各地,後續維護很痛苦。

方案三:AsyncTask(推薦)

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 起已被標記為廢棄。新項目裡的標準選擇是:

  • Kotlin 協程:配合 lifecycleScope / viewModelScope 和 withContext(Dispatchers.IO),代碼是同步風格但實際異步,還能自動跟隨生命週期取消。
  • Thread + Handler:老項目裡仍然常見,理解它有助於讀懂現有代碼。
  • OkHttp / Retrofit 的異步回調:網絡請求場景直接用庫自帶的異步能力,不必自己開線程。

但無論用哪種方案,那兩條鐵律永遠不變:不要阻塞主線程,不要跨線程碰 UI。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved