Android 源码(6) --- 异步消息机制Handler、Looper、MessageQueue

本文深入解析了Android中的消息处理机制,包括Handler、Looper和MessageQueue的初始化过程,以及消息的发送与处理流程。通过源码分析,揭示了主线程与子线程中消息循环的工作原理。

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

Handler、Looper、MessageQueue 初始化

  • 1.在 UI 线程创建 Handler,通常直接new Handler;
private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            }
        }
UI Thread 初始Handler化时 对Looper进行初始化过程, main()是在 UI Thread 启动时调用

```
 public static void main(String[] args) {
        SamplingProfilerIntegration.start();

        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        EventLogger.setReporter(new EventLoggingReporter());

        Security.addProvider(new AndroidKeyStoreProvider());

        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
```
查看一下代码,主要关注一下:Looper.prepareMainLooper();

```
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

public static void prepare() {
        prepare(f);
    }

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));
_    }
```
以上是UI Thread 初始化new Handler 调用过程
  • 2.接下来看一下 Other Thread 初始化调用。

    Looper.prepare();
    private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                }
            }

    查看下Looper.prepare();

    public static void prepare() {
            prepare(true);
        }
    
    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));
    _    }
    
  • 3.其他用法: 在其他地方需要用到Handler,并且需要刷新UI时,不通过Looper.prepare();调用,通过Looper.getMainLooper()也可以;

    ` Handler mHandler = new Handler(Looper.getMainLooper());

    class Looper{
    public static Looper getMainLooper() {
    synchronized (Looper.class) {
    return sMainLooper;
    }
    }
    } `

  • 4.MessageQueue 初始化


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

    Looper 在初始化时创建一个关联MessageQueue,一个线程中对应一个Looper & MessageQueue

  • Handler 初始化

    “`
    // 常用构造
    public Handler(Callback callback) {
    this(callback, false);
    }

    public Handler(Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
    final Class

异步消息

  • 1.调用,存储消息

    mHandler.sendMessage(new Message());
    mHandler.post();
    mHandler.postDelay();

    追踪一下不难发现,最后都走的一个地方

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            msg.target = this;
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            return queue.enqueueMessage(msg, uptimeMillis);
        }
这样看msg.target = this;msg.target就是Handler自己,而MessageQueue就是Looper中关联的对象,而enqueueMessage()中是对message保存,进行Message.next()按时间排序。
  • 2.消费
    Looper.loop()是对MessageQueue的消费
     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.recycleUnchecked();
        }
    }

看到loop()中,添加了一个死循环,不断去轮训MessageQueue中的队列是否为null,返回或者取出来继续执行 msg.target.dispatchMessage(msg);在最开始我们看到msg.target就是Handler本身

    public static Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 101) {
                    Log.i(TAG, "接收到handler消息...");
                }
            }
        };

而handleMessage就是我们重写的回调方法。

  • 3.一张图梳理一下流程
    流程图
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值