目录
Q1:用一句话概括Handler,并简述其原理?
(1)Handler是什么?
(2)Handler的原理是什么?
(3)Handler有什么作用?
(4)为什么使用handler,MessageQueue,Looper?
(5)Android为什么要设计只能通过Handler机制更新UI呢?
(6)Handler怎么用?
(7)Android中更新UI的几种方式:
(8)使用Handler时候遇到的问题?
(9)谷歌官方开发文档中关于对Handler的介绍:
Handler通常被我们用来做主线程与子线程之间的通信工具,它的应用非常广泛,可以说只要有异步线程与主线程通信的地方就一定会有 Handler。
一、Handler封装了消息的发送(主要包括消息发送给谁,以及如何去发送。默认情况下消息都是发送给Handler自己)。
二、Looper:轮询,消息封装的一个载体,
1、Looper内部包含一个消息队列也就是MessageQueue,所有的Handler发送的消息都走向这个消息队列;
2、Looper.looper方法,就是一个死循环,不断地从MessageQueue取消息,如有消息就处理,没有就阻塞;
三、MessageQueue,就是一个消息队列,可以添加消息,并处理消息。
四、Handler也很简单,内部会跟Looper进行关联,也就是说在Handler的内部可以找到Looper,找到了Looper也就找到了MessageQueue,在Handler中发送消息,其实就是向MessageQueue队列中发送消息。
总结:Handler负责发送消息,Looper负责接收Handler发送的消息,并直接把消息回传给Handler自己,MessageQueue就是一个存储消息的容器。
主线程无法进行时间比较繁长的任务,所以需要子线程进行处理,然而子线程无法进行UI的界面更新,所以我们需要使用handler来传递消息给主线程,让其完成UI的更新。由于主线程和子线程进行不同的时间工作,所要需要用MessageQueue来存放子线程的消息,Looper取出消息交给主线程响应。
最根本的目的就是解决多线程并发问题。
假如在一个Activity当中,有多个线程去更新UI,并且都没有加锁机制,那么会产生什么样子的问题?
答案是:更新界面错乱。
如果对更新UI的操作都进行加锁处理的话又会产生什么样子的问题?
答案是:性能下降。
出于对以上问题的考虑,android给我们提供了一套更新UI的机制,我们只需要遵循这样的机制就行了,而根本不用去关心多线程问题,所有的更新UI的操作,都是在主线程的消息队列当中去轮询处理的。
A Handler allows you to send and process Message and Runable 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 message and
runnables to that message queue and execute them as they come out of the message queue.
翻译:一个Handler允许你发送和处理跟一个Thread的MessageQueue相关的Message和Runable对象。每个Handler实例都跟一个单独的Thread以及该Thread创建的MessageQueue相关。当你创建一个Handler的时候,这个Handler就跟一个Thread以及该Thread创建的MessageQueue绑定在一起,所以,这个Handler将会传递messages和runnables给那个MessageQueue,并且处理来自这个MessageQueue的messages和runnables。
解释:我们创建一个Handler的时候,它会跟一个默认的Thread绑定,这个默认的Thread中就有一个MessageQueue(消息队列)。
When a process is created for your application, its main thread is dedicated(专用于) to running a message queue that takes care of managing the top-level application objects(activities,broadcast receivers .etc) and any windows they create.You can create you own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessge methods as before,but from your new thread. The given Runnable or Message will then be scheduled(列入计划表) in the Handler's message queue and processed when appropriate(适当的时候).
当我们创建一个application的时候,它就会自动创建一个process(进程),这个process的main thread(即application的主线程,也是UI线程)是一个ActivityThread,main thread会默认创建一个Looper,这个Looper就和主线程及其MessageQueue产生了联系。这个main thread 专门用来运行一个message queue,这个message queue用于管理顶级的application对象(例如activities,broadcast receivers等)和它们创建的windows。你也可以创建自己的threads,这些threads可以通过Handler的post or sendMessge methods跟main thread联系。给定的Runnable or Message将会被放入message queue ,并且在合适的时候会被处理。