Message
获取消息
- Message.obtain();
从消息池获取消息
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}
- mHandle.obtainMessage();
或Message.obtain(mHandle, what);
或Message.obtain(mHandle, what, obj);
或Message.obtain(mHandle, what, arg1, arg2);
等等......
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
注意:这个不能mHandle.sendMessage(msg);
而应该msg.sendToTarget();
1,Message设置数据
Bundle data = new Bundle();
data.putString(key, value);
data.putStringArray(key, value);
msg.setData(data);
2,handleMessage(Message msg)获取数据
Bundle data = msg.getData();
- Message.obtain(mHandle);
Handle
方法
- 发送消息,到MessageQueue中
post(Runnable)
postAtTime(Runnable, long)
postDelayed(Runnable, long)
sendEmptyMessage(int)
sendMessage(Message)
sendMessageAtTime(Message, long)
sendMessageDelayed(Message, long)
等等......
1,post和send两种类型,post传的是Runnable,底层是调用getPostMessage将Runnable转Message
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
- 将所有的Callbacks和Messages全部清除
mHandler.removeCallbacksAndMessages(null);
- 清除指定what的Message
mHandler.removeMessages(what);
Looper
- 子线程默认没有开启消息循环,没有创建消息队列,需要prepare(),loop()。
Looper.prepare():绑定一个Looper,底层会创建一个Looper,创建Looper的构造函数中又会创建一个消息队列,参见android消息机制.md
注意:此方法在当前线程只能调用一个,因为一个线程只能有一个Looper,否则会抛throw new RuntimeException("Only one Looper may be created per thread");
异常
Looper.loop():执行消息循环,直到消息队列循环结束
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}