当前位置: 代码迷 >> Android >> Android Handler线程间通讯机制分析
  详细解决方案

Android Handler线程间通讯机制分析

热度:74   发布时间:2016-05-01 19:30:14.0
Android Handler线程间通信机制分析
Looper: 循环处理消息队列

//用法:  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     * [email protected] #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
  相关解决方案