Android Handler线程间通信机制分析
16lz
2021-01-23
Looper: 循环处理消息队列
参考:http://blog.csdn.net/Innost/article/details/6055793
//用法: class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }//第一步,在TLS上创建一个Looper//TLS,thread local storage线程本地存储空间,也就是这个存储空间是和线程相关的,一个线程内有一个内部存储空间public static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper()); } /** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */// 从当前本地线程中得到loop对象,从中取出message队列,遍历其中的message并发送到其target// 注意msg.target.dispatchMessage(msg); public static final void loop() { Looper me = myLooper(); MessageQueue queue = me.mQueue; while (true) { Message msg = queue.next(); // might block //if (!me.mRun) { // break; //} if (msg != null) { if (msg.target == null) { // No target is a magic identifier for the quit message. return; } if (me.mLogging!= null) me.mLogging.println( ">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what ); msg.target.dispatchMessage(msg); if (me.mLogging!= null) me.mLogging.println( "<<<<< Finished to " + msg.target + " " + msg.callback); msg.recycle(); } } }// 再看看Handler中的该方法/** * Subclasses must implement this to receive messages. */ public void handleMessage(Message msg) { } /** * Handle system messages here. */ public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }
参考:http://blog.csdn.net/Innost/article/details/6055793
更多相关文章
- android 多线程下载原理
- Android中的线程模型
- android 的线程模型和AsyncTask
- Android中的多线程之handler
- 《第一行代码--Android》读书笔记之多线程与服务
- Android异步机制一:使用Thread+Handler实现非UI线程更新UI界面
- Android主线程消息循环
- android 多任务多线程断点下载
- [Android]Thread线程入门3--多线程