Android Looper类

本文详细介绍了Android中的Looper类,它是Android线程应用的重要组成部分。Looper主要用于初始化消息队列并分配消息,通过Looper.prepare()和Looper.loop()方法可以为线程创建和启动消息循环。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Looper类是Android中一个重要的类,用于处理Android线程方面的应用。它的主要作用是初始化MessageQueen,分配消息。描述如下

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.  
  
Most interaction with a message loop is through the Handler class.  


这是一个为线程运行消息循环的类。默认情况下,新建线程是没有消息循环的(主线程除外),可以通过创建一个Looper对象,调用Looper.prepare()方法来启动一个消息循环。

Looper类的源代码非常简单

private static final String TAG = "Looper";
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper;
final MessageQueue mQueue;
final Thread mThread;
volatile boolean mRun;
private Printer mLogging;
private static Looper mMainLooper = null;
sThreadLocal:线程本地化的变量,当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的副本,每一个线程都可以独立的改变自己的副本而不影响其他线程的副本,从而避免了竞争关系。

mQueue:消息队列。

mThread:与该Looper有关的线程。

mRun:判断线程是否开始,该变量为volatile修饰,线程每次使用该对象时,都会重新读取变量修改后的值。

mMainLooper:主线程Looper。

Looper.prepare()

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mRun = true;
        mThread = Thread.currentThread();
    }
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));
}
在构造函数中初始化了MessageQueen,和线程,prepare函数设置了sThreadLocal。

Looper.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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

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

这是Looper类中最重要的一个方法,首先先取出Looper对象,取出MessageQueen对象,然后在循环中用dispatchMessage来处理消息(此时target对象就是Handler),将消息不断的发送出去给相应的handler处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值