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

Android 消息機制 Handler 深度解析(源碼 + Demo)

編輯:關於 Android 程式設計

Handler 是開發人員在面試中最常見的問題之一。本文將從源碼層與使用方法兩個角度,較為全面地解讀 Handler 這套機制。

一、什麼是 Handler

Handler 是 Android 提供用來更新 UI 的一套機制,也是一套消息處理機制,既能用它發送消息,也能用它接收消息。

二、為什麼使用 Handler

Android 在設計之初就封裝了一套消息的創建、傳遞、處理機制。若不遵循這樣的機制,就無法更新 UI 資訊,並會拋出異常。

三、Handler 用法

1. postDelayed() 延時發送執行子線程——文字輪播 Demo(每隔一秒更新一次 TextView):

public class MainActivity extends AppCompatActivity {
    private TextView mTextView;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private String[] str = new String[]{"傲慢", "偏見", "僵屍"};
    private int index = 0;
    MyRunnable myRunnable = new MyRunnable();

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            index = index % 3;
            mTextView.setText(str[index]);
            index++;
            mHandler.postDelayed(myRunnable, 1000);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.tv);
        mHandler.postDelayed(myRunnable, 1000);
    }
}

2. sendMessage() 回調 handleMessage() 傳遞消息——在子線程得到資訊,發到主線程更新 TextView:

public class MainActivity extends AppCompatActivity {
    private TextView mTextView;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mTextView.setText(msg.obj + "" + "arg1=" + msg.arg1 + " arg2=" + msg.arg2);
            super.handleMessage(msg);
        }
    };

    private class Person {
        String name;
        int age;
        @Override
        public String toString() {
            return "name=" + name + " age=" + age;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.tv);
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.arg1 = 1;
                msg.arg2 = 2;
                Person person = new Person();
                person.name = "pig";
                person.age = 10;
                msg.obj = person;
                mHandler.sendMessage(msg);
            }
        }.start();
    }
}

3. sendToTarget() 傳遞消息——與第二種用法原理一致:

new Thread() {
    @Override
    public void run() {
        Message msg = mHandler.obtainMessage(); // 同樣可以獲取 Message 物件
        msg.arg1 = 1;
        msg.arg2 = 2;
        Person person = new Person();
        person.name = "pig";
        person.age = 10;
        msg.obj = person;
        msg.sendToTarget();
    }
}.start();

4. 使用 CallBack 截獲 Handler 的消息:

Handler mHandler = new Handler(new Handler.Callback() {
    // 傳入 CallBack 物件,重載的 handleMessage() 返回值為 boolean
    // 返回 false:先執行這個方法,再執行返回值為 void 的 handleMessage()
    // 返回 true:只執行這個方法
    @Override
    public boolean handleMessage(Message msg) {
        Toast.makeText(MainActivity.this, "截獲消息", Toast.LENGTH_SHORT).show();
        return false;
    }
}) {
    public void handleMessage(Message msg) {
        Toast.makeText(MainActivity.this, "發出消息", Toast.LENGTH_SHORT).show();
    }
};

四、為什麼只能透過 Handler 在主線程更新 UI

最根本的原因是解決多線程並發問題。假如同一個 Activity 中多個線程同時更新 UI 且沒有加鎖,會導致 UI 更新混亂;若加鎖,又會導致效能下降。使用 Handler 機制,我們不必操心多線程問題,所有更新 UI 的操作都在主線程消息隊列中輪詢處理。

五、Handler 機制的原理

Looper:(1)內部包含一個消息隊列 MessageQueue,所有 Handler 發送的消息都會進入這個隊列;(2)Looper.loop 方法是一個死循環,不斷從 MessageQueue 取消息,有就處理、沒有就阻塞。

MessageQueue:一個消息隊列,可以添加消息、處理消息。

Handler:內部會與 Looper 關聯,找到 Looper 也就找到了 MessageQueue。在 Handler 中發送消息,其實就是向 MessageQueue 發送消息。

總結:Handler 負責發送消息,Looper 負責接收消息並回傳給 Handler 自己,而 MessageQueue 是存儲消息的容器。

從源碼層看,Android 應用透過 ActivityThread 創建,它預設建立一個 Main 線程和一個 Looper,所有更新 UI 的操作都透過 Main 線程完成。查看 Looper.loop 源碼,確實是一個死循環:

public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
        throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;
    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();
    for (;;) {
        Message msg = queue.next(); // 沒有消息時可能阻塞
        if (msg == null) {
            return; // 隊列退出
        }
        msg.target.dispatchMessage(msg);
        msg.recycleUnchecked();
    }
}

可見是透過 msg.target.dispatchMessage() 處理消息,查看其源碼:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

從源碼看出:當有 CallBack 時會截獲消息,沒有則回調 handleMessage() 處理消息。而 SendMessage 系列方法最終也是把消息傳入消息隊列。

六、創建與線程相關的 Handler

在子線程建立 Handler,需先透過 Looper.prepare() 取得 Looper,並呼叫 Looper.loop() 輪詢消息隊列:

public Handler mHandler = new Handler() { // 主線程中的 Handler
    @Override
    public void handleMessage(Message msg) {
        Log.d("CurrentThread", Thread.currentThread() + ""); // 印出 Thread 的 ID
    }
};

class MyThread extends Thread {
    private Handler handler; // 子線程中的 Handler
    @Override
    public void run() {
        Looper.prepare(); // 取得 Looper
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.d("CurrentThread", Thread.currentThread() + "");
            }
        };
        Looper.loop(); // 輪詢消息隊列
    }
}

七、HandlerThread

HandlerThread 本質是一個 Thread,區別在於它在 run() 之後建立了一個含消息隊列的 Looper,這樣在子線程建立 Handler 時只需指定使用 HandlerThread 的 Looper,不必再呼叫 prepare()、loop()。Android 系統提供的 Handler 預設綁定 UI 線程的消息隊列,所以不能在其中做耗時操作;而非 UI 線程若想用消息機制,HandlerThread 內部的 Looper 最合適,它不會阻塞 UI 線程。

mHandlerThread = new HandlerThread("handler thread");
mHandlerThread.start();
Handler handler = new Handler(mHandlerThread.getLooper()) { // 透過 getLooper() 取得 Looper
    @Override
    public void handleMessage(Message msg) {
        Log.d("current thread", "" + Thread.currentThread());
    }
};
handler.sendEmptyMessage(1);

八、主線程與子線程信息交互

主線程與子線程的 Handler 互相發送消息,只要呼叫對方的 sendMessage() 即可,例如互相 sendMessageDelayed 就能實現週期性來回通信。

九、四種更新 UI 的方法

1、Handler.post();2、Handler.sendMessage()——這兩種本質上沒有區別,都是透過發送消息在 UI 線程更新 UI。

3、runOnUiThread():

public final void runOnUiThread(Runnable action) {
    if (Thread.currentThread() != mUiThread) {
        mHandler.post(action);
    } else {
        action.run();
    }
}

可見其本質仍是透過 Handler.post() 在 UI 線程更新 UI。

4、View.post():

public boolean post(Runnable action) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {
        return attachInfo.mHandler.post(action);
    }
    // 假設稍後 post 會成功
    ViewRootImpl.getRunQueue().post(action);
    return true;
}

查其源碼,一樣是採用 Handler.post() 更新 UI。

十、在非 UI 線程更新 UI

如果直接在子線程更新 UI,有時會成功、有時會拋出異常,原因在於:Activity 中有一個 ViewRootImpl 類,在其實例化之前系統不會檢測當前線程是否為 UI 線程,而它的實例化在 Activity 的 onResume() 中完成。所以若子線程沒休眠就直接更新 UI,系統還來不及檢測,就僥倖成功;而休眠一段時間後 ViewRootImpl 已實例化,此時更新 UI 就會拋出異常。當然,實際開發中我們仍應在 UI 線程更新 UI。

十一、常見的兩個問題

1、非 UI 線程更新 UI,拋出:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

2、子線程建立 Handler 缺少 Looper,拋出:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

查看源碼可知,沒有 Looper 就會拋出這個運行時異常:

mLooper = Looper.myLooper();
if (mLooper == null) {
    throw new RuntimeException(
        "Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved