1.Handler是什么?
原文:
A Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue. Each Handler instance is associated with a single thread and that thread’s message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it – from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
翻譯:
handler是用來接收和處理線程的消息隊列里的message/runnable對象的工具。每個handler實例關聯一個單獨的線程和這個的線程的消息隊列,handler實例會綁定到創建這個handler的線程。從那一刻起,handler會發送message/runnable到消息隊列,然后在message/runnable從消息隊列出來的時候處理它。
用法:處理線程之間消息的傳遞
2.為什么用handler?
考慮到java多線程的線程安全問題,android規定只能在UI線程修改Activity中的UI。為了在其他線程中可以修改UI,所以引入Handler,從其他線程傳消息到UI線程,然后UI線程接受到消息時更新線程。
3.handler用法
Message可攜帶的數據
//通常作標志位,作區分
message.what;(int)
//攜帶簡單數據
message.arg1;(int)
message.arg2;(int)
//攜帶object數據類型
message.obj;(object)
sendMessage 方式
接受消息並處理
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//處理消息
return false;
}
});
發送消息
mHandler.sendMessage(msg);
post 方式
因為需要等待之前發送到消息隊列里的消息執行完才能執行,所以需要異步等待。
new Thread(new Runnable() {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
}
});
}
}).start();
未完待續。。。