Android的Looper和Handler消息处理机制详解

Message:消息,其中包含了消息ID,消息处理对象以及处理的数据等,由MessageQueue统一列队,终由Handler处理。
Handler:处理者,负责Message的发送及处理。使用Handler时,需要实现handleMessage(Message msg)方法来对特定的Message进行处理,例如更新UI等。
MessageQueue:消息队列,用来存放Handler发送过来的消息,并按照FIFO规则执行。当然,存放Message并非实际意义的保存,而是将Message以链表的方式串联起来的,等待Looper的抽取。
Looper:消息泵,不断地从MessageQueue中抽取Message执行。因此,一个MessageQueue需要一个Looper。
Thread:线程,负责调度整个消息循环,即消息循环的执行场所。

Android系统的消息队列和消息循环都是针对具体线程的,一个线程可以存在(当然也可以不存在)一个消息队列和一个消 息循环(Looper),特定线程的消息只能分发给本线程,不能进行跨线程,跨进程通讯。但是创建的工作线程默认是没有消息循环和消息队列的,如果想让该 线程具有消息队列和消息循环,需要在线程中首先调用Looper.prepare()来创建消息队列,然后调用Looper.loop()进入消息循环。 如下例所示:

 
 
  1. LooperThread Thread {
  2. Handler mHandler;
  3.  
  4. run() {
  5. Looper.prepare();
  6.  
  7. mHandler = Handler() {
  8. handleMessage(Message msg) {
  9. }
  10. };
  11.  
  12. Looper.loop();
  13. }
  14. }

 

 
 
  1. //Looper类分析
  2. //没找到合适的分析代码的办法,只能这么来了。每个重要行的上面都会加上注释
  3. //功能方面的代码会在代码前加上一段分析
  4. public class Looper {
  5. //static变量,判断是否打印调试信息。
  6. private static final boolean DEBUG = false;
  7. private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
  8. // sThreadLocal.get() will return null unless you've called prepare().
  9. //线程本地存储功能的封装,TLS,thread local storage,什么意思呢?因为存储要么在栈上,例如函数内定义的内部变量。要么在堆上,例如new或者malloc出来的东西
  10. //但是现在的系统比如Linux和windows都提供了线程本地存储空间,也就是这个存储空间是和线程相关的,一个线程内有一个内部存储空间,这样的话我把线程相关的东西就存储到
  11. //这个线程的TLS中,就不用放在堆上而进行同步操作了。
  12. private static final ThreadLocal sThreadLocal = new ThreadLocal();
  13. //消息队列,MessageQueue,看名字就知道是个queue..
  14. final MessageQueue mQueue;
  15. volatile boolean mRun;
  16. //和本looper相关的那个线程,初始化为null
  17. Thread mThread;
  18. private Printer mLogging = null;
  19. //static变量,代表一个UI Process(也可能是service吧,这里默认就是UI)的主线程
  20. private static Looper mMainLooper = null;
  21. /** Initialize the current thread as a looper.
  22. * This gives you a chance to create handlers that then reference
  23. * this looper, before actually starting the loop. Be sure to call
  24. * {@link #loop()} after calling this method, and end it by calling
  25. * {@link #quit()}.
  26. */
  27. //往TLS中设上这个Looper对象的,如果这个线程已经设过了looper的话就会报错
  28. //这说明,一个线程只能设一个looper
  29. public static final void prepare() {
  30. if (sThreadLocal.get() != null) {
  31. throw new RuntimeException("Only one Looper may be created per thread");
  32. }
  33. sThreadLocal.set(new Looper());
  34. }
  35. /** Initialize the current thread as a looper, marking it as an application's main
  36. * looper. The main looper for your application is created by the Android environment,
  37. * so you should never need to call this function yourself.
  38. * {@link #prepare()}
  39. */
  40. //由framework设置的UI程序的主消息循环,注意,这个主消息循环是不会主动退出的
  41. //
  42. public static final void prepareMainLooper() {
  43. prepare();
  44. setMainLooper(myLooper());
  45. //判断主消息循环是否能退出....
  46. //通过quit函数向looper发出退出申请
  47. if (Process.supportsProcesses()) {
  48. myLooper().mQueue.mQuitAllowed = false;
  49. }
  50. }
  51. private synchronized static void setMainLooper(Looper looper) {
  52. mMainLooper = looper;
  53. }
  54. /** Returns the application's main looper, which lives in the main thread of the application.
  55. */
  56. public synchronized static final Looper getMainLooper() {
  57. return mMainLooper;
  58. }
  59. /**
  60. * Run the message queue in this thread. Be sure to call
  61. * {@link #quit()} to end the loop.
  62. */
  63. //消息循环,整个程序就在这里while了。
  64. //这个是static函数喔!
  65. public static final void loop() {
  66. Looper me = myLooper();//从该线程中取出对应的looper对象
  67. MessageQueue queue = me.mQueue;//取消息队列对象...
  68. while (true) {
  69. Message msg = queue.next(); // might block取消息队列中的一个待处理消息..
  70. //if (!me.mRun) {//是否需要退出?mRun是个volatile变量,跨线程同步的,应该是有地方设置它。
  71. // break;
  72. //}
  73. if (msg != null) {
  74. if (msg.target == null) {
  75. // No target is a magic identifier for the quit message.
  76. return;
  77. }
  78. if (me.mLogging!= null) me.mLogging.println(
  79. ">>>>> Dispatching to " + msg.target + " "
  80. + msg.callback + ": " + msg.what
  81. );
  82. msg.target.dispatchMessage(msg);
  83. if (me.mLogging!= null) me.mLogging.println(
  84. "<<<<< Finished to " + msg.target + " "
  85. + msg.callback);
  86. msg.recycle();
  87. }
  88. }
  89. }
  90. /**
  91. * Return the Looper object associated with the current thread. Returns
  92. * null if the calling thread is not associated with a Looper.
  93. */
  94. //返回和线程相关的looper
  95. public static final Looper myLooper() {
  96. return (Looper)sThreadLocal.get();
  97. }
  98.  
  99. /**
  100. * Control logging of messages as they are processed by this Looper. If
  101. * enabled, a log message will be written to printer
  102. * at the beginning and ending of each message dispatch, identifying the
  103. * target Handler and message contents.
  104. *
  105. * @param printer A Printer object that will receive log messages, or
  106. * null to disable message logging.
  107. */
  108. //设置调试输出对象,looper循环的时候会打印相关信息,用来调试用最好了。
  109. public void setMessageLogging(Printer printer) {
  110. mLogging = printer;
  111. }
  112. /**
  113. * Return the {@link MessageQueue} object associated with the current
  114. * thread. This must be called from a thread running a Looper, or a
  115. * NullPointerException will be thrown.
  116. */
  117. public static final MessageQueue myQueue() {
  118. return myLooper().mQueue;
  119. }
  120. //创建一个新的looper对象,
  121. //内部分配一个消息队列,设置mRun为true
  122. private Looper() {
  123. mQueue = new MessageQueue();
  124. mRun = true;
  125. mThread = Thread.currentThread();
  126. }
  127.  
  128. public void quit() {
  129. Message msg = Message.obtain();
  130. // NOTE: By enqueueing directly into the message queue, the
  131. // message is left with a null target. This is how we know it is
  132. // a quit message.
  133. mQueue.enqueueMessage(msg, 0);
  134. }
  135.  
  136. /**
  137. * Return the Thread associated with this Looper.
  138. */
  139. public Thread getThread() {
  140. return mThread;
  141. }
  142. //后面就简单了,打印,异常定义等。
  143. public void dump(Printer pw, String prefix) {
  144. pw.println(prefix + this);
  145. pw.println(prefix + "mRun=" + mRun);
  146. pw.println(prefix + "mThread=" + mThread);
  147. pw.println(prefix + "mQueue=" + ((mQueue != null) ? mQueue : "(null"));
  148. if (mQueue != null) {
  149. synchronized (mQueue) {
  150. Message msg = mQueue.mMessages;
  151. int n = 0;
  152. while (msg != null) {
  153. pw.println(prefix + " Message " + n + ": " + msg);
  154. n++;
  155. msg = msg.next;
  156. }
  157. pw.println(prefix + "(Total messages: " + n + ")");
  158. }
  159. }
  160. }
  161.  
  162. public String toString() {
  163. return "Looper{"
  164. + Integer.toHexString(System.identityHashCode(this))
  165. + "}";
  166. }
  167.  
  168. static class HandlerException extends Exception {
  169.  
  170. HandlerException(Message message, Throwable cause) {
  171. super(createMessage(cause), cause);
  172. }
  173.  
  174. static String createMessage(Throwable cause) {
  175. String causeMsg = cause.getMessage();
  176. if (causeMsg == null) {
  177. causeMsg = cause.toString();
  178. }
  179. return causeMsg;
  180. }
  181. }
  182. }
  183.  
  184. 那怎么往这个消息队列中发送消息呢??调用looperstatic函数myQueue可以获得消息队列,这样你就可用自己往里边插入消息了。不过这种方法比较麻烦,这个时候handler类就发挥作用了。先来看看handler的代码,就明白了。
  185. class Handler{
  186. ..........
  187. //handler默认构造函数
  188. public Handler() {
  189. //这个if是干嘛用的暂时还不明白,涉及到java的深层次的内容了应该
  190. if (FIND_POTENTIAL_LEAKS) {
  191. final Class<? extends Handler> klass = getClass();
  192. if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
  193. (klass.getModifiers() & Modifier.STATIC) == 0) {
  194. Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
  195. klass.getCanonicalName());
  196. }
  197. }
  198. //获取本线程的looper对象
  199. //如果本线程还没有设置looper,这回抛异常
  200. mLooper = Looper.myLooper();
  201. if (mLooper == null) {
  202. throw new RuntimeException(
  203. "Can't create handler inside thread that has not called Looper.prepare()");
  204. }
  205. //无耻啊,直接把looper的queue和自己的queue搞成一个了
  206. //这样的话,我通过handler的封装机制加消息的话,就相当于直接加到了looper的消息队列中去了
  207. mQueue = mLooper.mQueue;
  208. mCallback = null;
  209. }
  210. //还有好几种构造函数,一个是带callback的,一个是带looper的
  211. //由外部设置looper
  212. public Handler(Looper looper) {
  213. mLooper = looper;
  214. mQueue = looper.mQueue;
  215. mCallback = null;
  216. }
  217. // 带callback的,一个handler可以设置一个callback。如果有callback的话,
  218. //凡是发到通过这个handler发送的消息,都有callback处理,相当于一个总的集中处理
  219. //待会看dispatchMessage的时候再分析
  220. public Handler(Looper looper, Callback callback) {
  221. mLooper = looper;
  222. mQueue = looper.mQueue;
  223. mCallback = callback;
  224. }
  225. //
  226. //通过handler发送消息
  227. //调用了内部的一个sendMessageDelayed
  228. public final boolean sendMessage(Message msg)
  229. {
  230. return sendMessageDelayed(msg, 0);
  231. }
  232. //FT,又封装了一层,这回是调用sendMessageAtTime了
  233. //因为延时时间是基于当前调用时间的,所以需要获得绝对时间传递给sendMessageAtTime
  234. public final boolean sendMessageDelayed(Message msg, long delayMillis)
  235. {
  236. if (delayMillis < 0) {
  237. delayMillis = 0;
  238. }
  239. return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
  240. }
  241. public boolean sendMessageAtTime(Message msg, long uptimeMillis)
  242. {
  243. boolean sent = false;
  244. MessageQueue queue = mQueue;
  245. if (queue != null) {
  246. //把消息的target设置为自己,然后加入到消息队列中
  247. //对于队列这种数据结构来说,操作比较简单了
  248. msg.target = this;
  249. sent = queue.enqueueMessage(msg, uptimeMillis);
  250. }
  251. else {
  252. RuntimeException e = new RuntimeException(
  253. this + " sendMessageAtTime() called with no mQueue");
  254. Log.w("Looper", e.getMessage(), e);
  255. }
  256. return sent;
  257. }
  258. //还记得looper中的那个消息循环处理吗
  259. //从消息队列中得到一个消息后,会调用它的target的dispatchMesage函数
  260. //message的target已经设置为handler了,所以
  261. //最后会转到handler的msg处理上来
  262. //这里有个处理流程的问题
  263. public void dispatchMessage(Message msg) {
  264. //如果msg本身设置了callback,则直接交给这个callback处理了
  265. if (msg.callback != null) {
  266. handleCallback(msg);
  267. } else {
  268. //如果该handler的callback有的话,则交给这个callback处理了---相当于集中处理
  269. if (mCallback != null) {
  270. if (mCallback.handleMessage(msg)) {
  271. return;
  272. }
  273. }
  274. //否则交给派生处理,基类默认处理是什么都不干
  275. handleMessage(msg);
  276. }
  277. }
  278. ..........
  279. }
  280.  
  281. 生成
  282. Message msg = mHandler.obtainMessage();
  283. msg.what = what;
  284. msg.sendToTarget();
  285.  
  286. 发送
  287. MessageQueue queue = mQueue;
  288. if (queue != null) {
  289. msg.target = this;
  290. sent = queue.enqueueMessage(msg, uptimeMillis);
  291. }
  292.  
  293. Handler.javasendMessageAtTime(Message msg, long uptimeMillis)方法中,我们看到,它找到它所引用的MessageQueue,然后将Messagetarget设定成自己(目的是为了在处理消息环节,Message能找到正确的Handler),再将这个Message纳入到消息队列中。
  294. 抽取
  295. Looper me = myLooper();
  296. MessageQueue queue = me.mQueue;
  297. while (true) {
  298. Message msg = queue.next(); // might block
  299. if (msg != null) {
  300. if (msg.target == null) {
  301. // No target is a magic identifier for the quit message.
  302. return;
  303. }
  304. msg.target.dispatchMessage(msg);
  305. msg.recycle();
  306. }
  307. }
  308.  
  309. Looper.javaloop()函数里,我们看到,这里有一个死循环,不断地从MessageQueue中获取下一个(next方法)Message,然后通过Message中携带的target信息,交由正确的Handler处理(dispatchMessage方法)。
  310. 处理
  311. if (msg.callback != null) {
  312. handleCallback(msg);
  313. } else {
  314. if (mCallback != null) {
  315. if (mCallback.handleMessage(msg)) {
  316. return;
  317. }
  318. }
  319. handleMessage(msg);
  320. }
  321.  
  322. Handler.javadispatchMessage(Message msg)方法里,其中的一个分支就是调用handleMessage方法来处理这条Message,而这也正是我们在职责处描述使用Handler时需要实现handleMessage(Message msg)的原因。
  323. 至于dispatchMessage方法中的另外一个分支,我将会在后面的内容中说明。
  324. 至此,我们看到,一个Message经由Handler的发送,MessageQueue的入队,Looper的抽取,又再一次地回到Handler的怀抱。而绕的这一圈,也正好帮助我们将同步操作变成了异步操作。
  325. 3)剩下的部分,我们将讨论一下Handler所处的线程及更新UI的方式。
  326. 在主线程(UI线程)里,如果创建Handler时不传入Looper对象,那么将直接使用主线程(UI线程)的Looper对象(系统已经帮我们创建了);在其它线程里,如果创建Handler时不传入Looper对象,那么,这个Handler将不能接收处理消息。在这种情况下,通用的作法是:
  327. class LooperThread extends Thread {
  328. public Handler mHandler;
  329. public void run() {
  330. Looper.prepare();
  331. mHandler = new Handler() {
  332. public void handleMessage(Message msg) {
  333. // process incoming messages here
  334. }
  335. };
  336. Looper.loop();
  337. }
  338. }
  339.  
  340. 在创建Handler之前,为该线程准备好一个LooperLooper.prepare),然后让这个Looper跑起来(Looper.loop),抽取Message,这样,Handler才能正常工作。
  341. 因此,Handler处理消息总是在创建Handler的线程里运行。而我们的消息处理中,不乏更新UI的操作,不正确的线程直接更新UI将引发异常。因此,需要时刻关心Handler在哪个线程里创建的。
  342. 如何更新UI才能不出异常呢?SDK告诉我们,有以下4种方式可以从其它线程访问UI线程:
  343. · Activity.runOnUiThread(Runnable)
  344. · View.post(Runnable)
  345. · View.postDelayed(Runnable, long)
  346. · Handler
  347. 其中,重点说一下的是View.post(Runnable)方法。在post(Runnable action)方法里,View获得当前线程(即UI线程)的Handler,然后将action对象postHandler里。在Handler里,它将传递过来的action对象包装成一个MessageMessagecallbackaction),然后将其投入UI线程的消息循环中。在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnablerun方法。而此时,已经路由到UI线程里,因此,我们可以毫无顾虑的来更新UI
  348. 4 几点小结
  349. · Handler的处理过程运行在创建Handler的线程里
  350. · 一个Looper对应一个MessageQueue
  351. · 一个线程对应一个Looper
  352. · 一个Looper可以对应多个Handler
  353. · 不确定当前线程时,更新UI时尽量调用post方法

转载请注明:安度博客 » Android的Looper和Handler消息处理机制详解


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值