一、handler是什么?
handler是android提供的更新UI的机制,也是一套消息处理机制,可用其发送消息、处理消息。
二、为什么是handler?
android在设计的时候,就封装了这套消息的发送、传递、处理机制,如果不遵循这种机制更新UI则抛异常。
三、用法
mHandler.sendMessage(msg);
post(Runnable r)
removeMessages(int what)
removeCallbacks(Runnable r)
四、技术点
1:
// Message msg=new Message();//直接创建一个Message // Message msg=mHandler.obtainMessage(); // Message msg=Message.obtain();msg.setTaget(mHandler); // Message msg=Message.obtain(mHandler); 区别 obtainMessage()代码流程:
/**
* Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
* creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
* If you don't want that facility, just call Message.obtain() instead.
*/
public final Message obtainMessage()
{
return Message.obtain(this);
}
/**
* Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
* @param h Handler to assign to the returned Message object's <em>target</em> member.
* @return A Message object from the global pool.
*/
public static Message obtain(Handler h) {
Message m = obtain();
m.target = h;
return m;
}
/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
目的是为了避免重复创建Message
*/
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();
}
2、
/**
* Constructor associates this handler with the {@link Looper} for the
* current thread and takes a callback interface in which you can handle
* messages.
*
* If this thread does not have a looper, this handler won't be able to receive messages
* so an exception is thrown.
*
* @param callback The callback interface in which to handle messages, or null.
*/
public Handler(Callback callback) {
this(callback, false);
}
//by zz
@SuppressLint("HandlerLeak")
Handler mHandler = new Handler(new Handler.Callback() {
//拦截消息,false继续传递,true传递停止(类似View事件分发的返回值作用)
@Override
public boolean handleMessage(Message msg) {
Toast.makeText(MainActivity.this, (String) msg.obj+"aaa",Toast.LENGTH_SHORT).show();
return false;
}
}) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Toast.makeText(MainActivity.this, (String) msg.obj,Toast.LENGTH_SHORT).show();
}
};