Looper、MessageQueue
官方解释
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
一个Looper类似一个消息泵。它本身是一个死循环,不断地从MessageQueue中提取Message或者Runnable。Android系统主线程才会创建Looper,子线程需要手动创建(类似iOS的RunnLoop),Looper创建首先调用Looper.prepare()方法,这里prepare不能多次调用,否则程序会crash,Looper创建以后在调用Looper.loop()方法,让Looper处于阻塞状态。
获取Looper有两种方法:
- Looper.myLooper()
- Looper.getMainLooper()
myLooper方法会获取当前线程的Looper,getMainLooper会获取主线程的Looper。
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.
程序启动的时候,会创建一个主线程(包括UI绘制,系统事件处理,用户输入事件,Service,Alarm),主线程不是线程安全,如果在异步线程中获取UI数据,然后在子线程里更新UI的时候会引起Crash,这时候就需要通过某种机制在子线程可以调用主线程的UI绘制逻辑,怎么办?这就是Handler需要做的事情。
Handler构造方法有:
- Handler()
- Hanlder(Looper looper)
- Handler(Handler.Callback)
- Handler(Looper, Handler.Callback)
其中第一个无参数构造方法,会将Handler与创建Handler的当前线程进行绑定,这样就可以在子线程里拿到主线程的hanlder,然后通过Post/SendMessage两种方式将Runnable或者Message发送至主线程的MessageQueue,然后主线程的Looper从阻塞态回复处理MessageQueue里的消息。
Post
Post允许把一个Runnable对象入队到MessageQueue中。它的方法有:
- post(Runnable)
- postAtTime(Runnable, long)
- postDelayed(Runnable, long)
对于Handler的Post方式来说,它会传递一个Runnable对象到消息队列中,在这个Runnable对象中,重写run()方法。一般在这个run()方法中写入需要在UI线程上的操作。
sendMessage
sendMessage允许把一个包含消息数据的Message对象压入到MessageQueue中。它的方法有:
- sendEmptyMessage(int)
- sendMessage(Message)
- sendMessageAtTime(Message,long)
- sendMessageDelayed(Message,long)
Handler如果使用sendMessage的方式把消息入队到消息队列中,需要传递一个Message对象,而在Handler中,需要重写handleMessage()方法,用于获取工作线程传递过来的消息,此方法运行在UI线程上。
Message
message是一个final类,所以不可被继承。
网友评论