Android消息机制---Looper工作原理

一、简述

  Google官方介绍:

 Class used to run a message loop for a thread.  Threads by default do not have a message loop associated with them; to create 
one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.

大致意思:Looper是用来为一个线程执行一个消息循环的,线程默认是没有循环消息与他们绑定到一块的,为了创建一个Looper对象,在线程中调用prepare()来运行这个循环,
然后开始循环处理消息,直到这个循环结束。大多数与消息循环交互是通过Handler()。
个人理解:在Android的消息机制中Looper扮演着重要的角色。顾名思义,Looper就是一个循环器。具体说来他会一直不停的从MessageQueue中查看是否有新信息,如果有新消息就立即处理,否者就一直处在阻塞状态。
  

二、源码分析

    构造方法源码:

    我们看一下Looper的属性以及构造方法:

    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    private static Looper sMainLooper;  // guarded by Looper.class

    final MessageQueue mQueue;
    final Thread mThread;
    sThreadLocal:用于存储Looper对象;

    mQueue:Looper所管理的MessageQueue对象;

    mThread:Looper所属的线程;

   

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

    在构造方法中,创建一个MessageQueue对象同时获取Looper当前所属线程,然后将Looper对象利用ThreadLocal将其保存在当前线程中。

prepare()方法源码:

   我们在上面的代码中看到了Looper的构造函数是私有的,因此Goggle为开发者在创建Looper对象时提供了prepare()方法:

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));
    }

   在prepare()方法中首先判断当前线程中是否已经存在了Looper对象,如果当前线程没有Looper则立即创建同时将Looper对象保存起来,否则抛出异常!通过上面的prepare()方法可以创建Looper对象,而且也保证了一个线程中只能有一个Looper。

   Looper对象创建以后,还要调用Looper的loop()方法:loop()方法:

public static void loop() {
        //获取到当前线程的Looper对象
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //获取Looper对象创建的MessageQueue
        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循环
        for (;;) {
            //获取MessageQueue中的Message
            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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            //调用该条Message所属Handler的dispatchMessage(msg)方法处理消息
            msg.target.dispatchMessage(msg);

            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();
        }
    }

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }
    首先获取当前线程的Looper对象,同时也要判断获取到的当前Looper对象是否为空,如果为空则抛出异常:Looper.prepare() was't called on this thread.这也解释了在调用loop()方法之前必须调用prepare()方法。

   其他方法:

  getMainLooper():返回当前应用程序中依赖主线程的looper,
   getThread():返回和looper相关联的线程。
   mylooper():返回和当前线程关联的looper,如果没有looper与当前线程关联,则返回null。
   myQueue():返回和当前线程相关联的消息队列,使用这个方法,必须确保当前线程与looper相关联。
   prepareMainLooper():初始化与主线程相关联的looper。
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值