Looper源码分析

Android Looper源码分析

//该类管理消息队列 负责消息循环

class Looper{

        //sThreadLocal将该类与当前线程绑定 学过Java EE的童鞋对此类一定很是熟悉

private static final ThreadLocal sThreadLocal = new ThreadLocal();

        //消息队列 维护消息

        final MessageQueue mQueue;

        /./当前Looper对象的引用

       private static Looper mMainLooper = null;

       // 初始化Looper对象将Looper对象与当前线程绑定 

       public static final void prepare() {
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        sThreadLocal.set(new Looper());

      }

      //Looper构造函数 初始化消息队列 获取当前线程的引用...完成初始化

      private Looper() {
        mQueue = new MessageQueue();
        mRun = true;
        mThread = Thread.currentThread();
      }

     //获取与UI线程绑定的Looper对象 默认情况下 只有UI线程 系统才会为其开启Looper

      private synchronized static void setMainLooper(Looper looper) {
        mMainLooper = looper;
     }

     //获取与当前线程绑定的Looper对象

     public static final Looper myLooper() {
        return (Looper)sThreadLocal.get();
     }

     //消息循环

     public static final void loop() {

        //获取与当前线程绑定的Looper对象
        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();
            }
        }
    }

}

Looper源码不是很长 很好分析 

建议大家去阅读Adnroid源码 分析之

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值