关于Handler学习的一些自我小结
2017-03-02 16:11
120 查看
Handler在Android实现异步扮演了一个很重要的角色,所以记录下学习之后的一些小结。
关于线程使用Handler:
在实例化Handler对象前需先执行Looper.prepare(),查看源码,我们可以看到Looper,MessageQueue,Thread是一一对应的关系,一个Thread里面只能有一个Looper,同时我们可以看到sThreadLocal.set(new Looper(quitAllowed));这行代码,发现ThreadLocal中管理的就是Looper。ThreadLocal的作用是为多个线程操作的同一个变量提供不同的数据副本,让不同的线程相互之间操作不受影响。Looper.loop()就是开始轮询消息队列,当不想轮询的时候可以调用Looper.quit();
Handler发消息的方法有post(),postAtTime(),postDelayed(),postAtFrontOfQueue()这几种,其中前面三种最后都是走下面这个方法:
而postAtFrontOfQueue()相当于是把消息直接放到消息队列的最前面,它走的是下面这个方法:
对比之后我们发现就是,enqueueMessage()方法的第三个参数的值有所不同,我们来看下enqueueMessage()方法:
第三个参数就是决定消息入队先后顺序的,值越小代表先入队,先处理。我们看到msg.target = this;这句代码,这个this就是handler,作用就是标识这个message的来源,同时又该交给谁处理。
接下来就是消息出队的过程了,Looper轮询消息队列,当有message,就取出分配给对应的handler处理,而消息队列里面没有message时就会阻塞loop()方法,我们点开Looper的loop()方法,发现其中有这么一句msg.target.dispatchMessage(msg);前面我们就讲了这个msg.target就是handler,所以这就是消息的出队,附上loop()方法的源码:
消息出队之后就是handler处理消息了。我们来看到
我们发现handleMessage()是一个空方法,需要我们自己去实现处理消息。大致就是如此,有错误的地方敬请告知,谢谢。
关于线程使用Handler:
class TestThread extends Thread{ public Handler mHandler; public void run(){ Looper.prepare(); mHandler=new Handler(){ public void handleMessage(Message msg){ } }; Looper.loop(); } }
在实例化Handler对象前需先执行Looper.prepare(),查看源码,我们可以看到Looper,MessageQueue,Thread是一一对应的关系,一个Thread里面只能有一个Looper,同时我们可以看到sThreadLocal.set(new Looper(quitAllowed));这行代码,发现ThreadLocal中管理的就是Looper。ThreadLocal的作用是为多个线程操作的同一个变量提供不同的数据副本,让不同的线程相互之间操作不受影响。Looper.loop()就是开始轮询消息队列,当不想轮询的时候可以调用Looper.quit();
/** Initialize the current thread as a looper. * This gives you a chance to create handlers that then reference * this looper, before actually starting the loop. Be sure to call * {@link #loop()} after calling this method, and end it by calling * {@link #quit()}. */ public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); } private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); }
Handler发消息的方法有post(),postAtTime(),postDelayed(),postAtFrontOfQueue()这几种,其中前面三种最后都是走下面这个方法:
public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); }
而postAtFrontOfQueue()相当于是把消息直接放到消息队列的最前面,它走的是下面这个方法:
public final boolean sendMessageAtFrontOfQueue(Message msg) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, 0); }
对比之后我们发现就是,enqueueMessage()方法的第三个参数的值有所不同,我们来看下enqueueMessage()方法:
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); }
第三个参数就是决定消息入队先后顺序的,值越小代表先入队,先处理。我们看到msg.target = this;这句代码,这个this就是handler,作用就是标识这个message的来源,同时又该交给谁处理。
接下来就是消息出队的过程了,Looper轮询消息队列,当有message,就取出分配给对应的handler处理,而消息队列里面没有message时就会阻塞loop()方法,我们点开Looper的loop()方法,发现其中有这么一句msg.target.dispatchMessage(msg);前面我们就讲了这个msg.target就是handler,所以这就是消息的出队,附上loop()方法的源码:
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */ public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } try { msg.target.dispatchMessage(msg); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }
消息出队之后就是handler处理消息了。我们来看到
public void dispatchMessage(Message msg) { if (msg.callback != null) {//callback就是runnable封装成的 handleCallback(msg); } else { if (mCallback != null) {//mCallback就是实例化handler时我们传进去的 if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg);//当上面都没处理时走这个方法 } } /** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { }
我们发现handleMessage()是一个空方法,需要我们自己去实现处理消息。大致就是如此,有错误的地方敬请告知,谢谢。
相关文章推荐
- 关于 Angular2 学习的一些小结
- 关于近期学习java se篇的小结及一些学习路线的思考
- Android学习札记31:收集到的一些关于Handler和Runnable的问题(2)
- 关于职业工作和自我学习的一些思考
- 【非凡程序员】 关于今天学习指针的一些自我认知的问题,和学习Xcode的感悟
- ASP.NET中一些关于http对象的学习
- [自我学习用]Decompie破解一些软件的实例
- 学习WEB标准总结的一些CSS/XHTML知识小结第1/3页
- 学习中遇到的问题-关于set_new_handler()
- 关于学习编程的一些思考
- 关于面试学习的一些memory
- 最近在ArcGIS Engine开发中关于调用gp工具过程出现COM 组件的调用返回了错误 HRESULT E_FAIL 错误的解决方法 和 学习oracle中遇到的一些问题总结
- Git 一些关于 Git、Github 的学习资源
- 关于Linux中动态库的一些学习
- 关于C的一些学习笔记
- HandlerThread实现多线程操作_个人学习小结
- 关于C++的一些学习体会!
- 关于Flex的一些学习资料
- 关于UML使用和学习的一些想法
- 关于composer一些学习和理解