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

Android Handler、Thread 與 Runnable 更新 UI 的關係釐清

編輯:關於 Android 程式設計

寫一個小應用的時候,我碰到一個關於 Handler、Thread 與 Runnable 的問題,問了群裡不少人仍舊无解,翻查大量資料後才稍微理出頭緒,這裡記錄下來分享。

核心問題是:Thread 與 Runnable 的差別是什麼?它們在搭配 Handler 使用時又會造成什麼影響?先看一段會出錯的程式碼。

錯誤寫法:Thread 類內部 new 了一個 Activity

public class MainActivity extends Activity {
    TextView text1, text2;
    Button button;
    myThread th;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text1 = (TextView) findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                th = new myThread();
                th.start();
            }
        });
    }

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    text1.setText(msg.getData().getString("s1"));
                    text2.setText(msg.getData().getString("s1"));
                    break;
            }
            super.handleMessage(msg);
        }
    };
}

class myThread extends Thread {
    MainActivity ma = new MainActivity();   // 問題就在這一行

    public void run() {
        Bundle bundle = new Bundle();
        bundle.putString("s1", "fsdfsgfdsgdfgfdgdhshshs");
        bundle.putString("s2", "fsfsdgdshdhdshrehreherh");

        Message msg = new Message();
        msg.what = 1;
        msg.setData(bundle);
        ma.myHandler.sendMessage(msg);
    }
}

這段程式碼執行到 handler 更新 UI 的部分就會拋出空指標錯誤。

正確寫法:改用 Runnable

public class MainActivity extends Activity {
    TextView text1, text2;
    Button button;
    Thread th;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text1 = (TextView) findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                th = new Thread(runnable);
                th.start();
            }
        });
    }

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    text1.setText(msg.getData().getString("s1"));
                    text2.setText(msg.getData().getString("s1"));
                    break;
            }
            super.handleMessage(msg);
        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Bundle bundle = new Bundle();
            bundle.putString("s1", "fsdfsgfdsgdfgfdgdhshshs");
            bundle.putString("s2", "fsfsdgdshdhdshrehreherh");

            Message msg = new Message();
            msg.what = 1;
            msg.setData(bundle);
            MainActivity.this.myHandler.sendMessage(msg);   // 用外部限定符存取
        }
    };
}

這版本能正確更新 UI。

那 Thread 到底行不行?

找到問題後我又做了幾個小實驗,發現 Thread 其實也能用來更新 UI,關鍵在於怎麼參照 Handler:

public class MainActivity extends Activity {
    TextView text1, text2;
    Button button;
    myThread th;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        text1 = (TextView) findViewById(R.id.text1);
        text2 = (TextView) findViewById(R.id.text2);
        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                th = new myThread();
                th.start();
            }
        });
    }

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    text1.setText(msg.getData().getString("s1"));
                    text2.setText(msg.getData().getString("s1"));
                    break;
            }
            super.handleMessage(msg);
        }
    };

    class myThread extends Thread {
        public void run() {
            Bundle bundle = new Bundle();
            bundle.putString("s1", "fsdfsgfdsgdfgfdgdhshshs");
            bundle.putString("s2", "fsfsdgdshdhdshrehreherh");

            Message msg = new Message();
            msg.what = 1;
            msg.setData(bundle);
            MainActivity.this.myHandler.sendMessage(msg);   // 差別只在這裡
        }
    }
}

問題根源在哪

三段程式碼擺在一起,差異就很清楚了:錯誤版本在 myThread 裡 new MainActivity(),得到的是一個全新的、尚未執行 onCreate 的 Activity 物件,它的 text1、text2 全是 null,myHandler 也還沒綁上任何有效的 Context。空指標就是這麼來的。

正確做法有兩種,本質相同——都是「直接引用外層那個已存在的 Activity 實例」:

用 Runnable:Runnable 是內部類,可直接存取主執行緒的變數,寫 MainActivity.this.myHandler 即可。

用內部類繼承 Thread:利用內部類能自由存取外部類成員的特性,同樣寫 MainActivity.this.myHandler。

而錯誤版本把 myThread 寫成一個獨立的外部類,失去了這层关联,只能自己 new 一個 Activity,於是拿到的是空殼物件。

結論很簡單:不要在子執行緒中 new Activity。Activity 的生命週期由系統與 ActivityThread 管理,自行 new 出來的實例從未走過完整的初始化流程,任何操作都不可靠。

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