理解Android消息机制

本文深入解析Android中的消息机制,重点介绍Handler的运行原理,包括如何创建Handler与Looper,消息的发送、获取及分发过程。文章详细阐述了MessageQueue的工作流程,以及消息在不同线程间的传递机制。

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

Android的消息机制主要是指Handler的运行机制,Handler的主要作用是将一个任务切换到某个指定的线程中去执行,在实际开发中,通常用来在子线程切换到UI线程更新UI;
完整的Hanlder使用方式是这样的:

class HanlderThread extends Thread{
    Handler mHandler;
    @Override
    public void run() {
        Looper.prepare();
        mHandler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                //接受处理消息
            }
        };
        Looper.loop();
    }
}

为何要加 Looper.prepare()? 先看到Handler的构造方法:

public Handler(@Nullable Callback callback, boolean async) {
    if (FIND_POTENTIAL_LEAKS) {
        final Class<? extends Handler> klass = getClass();
        if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                (klass.getModifiers() & Modifier.STATIC) == 0) {
            Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                klass.getCanonicalName());
        }
    }

    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
                    + " that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

其中有一个判断, if (mLooper == null)则抛异常,也就是说创建Handler之前必须创建Looper,那么为什么我们平时使用的时候并没有看到Looper,那是因为在主线程中已经创建了Looper。
一、Looper
首先看到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));
}

先会去判断Looper是否已经存在,如果不存在则new一个,并保存在sThreadLocal中;sThreadLocal是一个ThreadLocal的变量,ThreadLocal是一个线程本地存储去,用来在指定的线程中存储数据,只有在指定的线程中可以获取到存储的数据;此处就是通过ThreadLocal将looper对象绑定到当前线程。所以通过looper就将Handler关联到当前线程;
二、发送消息
创建了Handler对象,接下来就是发送消息了,通常的步骤是:

//构建message对象
Message message = Message.obtain();
message.what = 1;
message.obj = "我要发消息";
mHandler.sendMessage(message);

从Handler源码可以看到,Handler发送消息的方式有send和post两类;其中post方法会调用getPostMessage()方法,构建一个Message,并将传入的Runnable赋值给Message.callabck变量。
最终都是调用sendMessageAtTime(Message msg, long uptimeMillis)方法:

public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
    MessageQueue queue = mQueue;
    if (queue == null) {
        RuntimeException e = new RuntimeException(
                this + " sendMessageAtTime() called with no mQueue");
        Log.w("Looper", e.getMessage(), e);
        return false;
    }
    return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
        long uptimeMillis) {
    msg.target = this;
    msg.workSourceUid = ThreadLocalWorkSource.getUid();

    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}

可以看到先是创建了MessageQueue对象,这个MessageQueue来自Looper中 new MessageQueue(quitAllowed);
最后调用了MessageQueue的enqueueMessage(msg, uptimeMillis)方法:

boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }

    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
          
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
           
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }
        if (needWake) {
            //next方法读取消息时,触发nativePollOnce方法结束等待
            nativeWake(mPtr);
        }
    }
    return true;
}

MessageQueue是一个单向链表的结构,发送消息后按照时间的先后顺序排列;

三、获取消息
消息发送后会开启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();

    // Allow overriding a threshold with a system prop. e.g.
    // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
    final int thresholdOverride =
            SystemProperties.getInt("log.looper."
                    + Process.myUid() + "."
                    + Thread.currentThread().getName()
                    + ".slow", 0);

    boolean slowDeliveryDetected = false;

    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
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
        // Make sure the observer won't change while processing a transaction.
        final Observer observer = sObserver;
        //省略部分无关代码
		......
		
        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        Object token = null;
        if (observer != null) {
            token = observer.messageDispatchStarting();
        }
        long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
        try {
            msg.target.dispatchMessage(msg);
            if (observer != null) {
                observer.messageDispatched(token, msg);
            }
        } catch (Exception exception) {
            if (observer != null) {
                observer.dispatchingThrewException(token, msg, exception);
            }
            throw exception;
        } finally {
            ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        //省略部分无关代码
		......
        msg.recycleUnchecked();
    }
}

先拿到MessageQueue,然后进入死循环调用MessageQueue的next()方法去拿到消息;

Message next() {
    //省略部分无关代码
	......
    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
        //native层处理等待
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }
    //省略部分无关代码
	......
}

其中也是一个无限循环,去获取Message,获取之后会将该message从队列中删除,如果没有message则挂起继续等待下一个message到来。
获取到message之后调用msg.target.dispatchMessage(msg)方法分发,其中msg.target就是当前Handler(在Handler的enqueueMessage方法中赋值),最终进入到Hanlder的dispatchMessage(msg)分发Message;
四、消息分发:
查看Hanlder的dispatchMessage(msg)方法:

public void dispatchMessage(@NonNull Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

可以看到分发的逻辑:
1、如果message的callback不为null,则调用message.callback.run(),此处的callback就是post方法系列中传入的Runnable,最终执行Runnable的run方法。
2、如果Handler的mCallback不为null,则调用mCallback.handleMessage(msg);
3、最后调用Handler自身的handleMessage(msg)方法。
总结:
创建Handler对象,在创建Handler对象的时候需要先获取Looper对象,Looper对象通过ThreadLocal与当前线程绑定,在Looper初始化的时候new MessageQueue;通过Handler的sendMessageAtTime 方法发送一个Message,然后调用MessageQueue的enqueueMessage方法按照时间先后顺序插入到消息队列;开启loop方法无限循环从MessageQueue的next方法获取Message,其中next方法也是通过无限循环从MessageQueue中取出Message,取出后将Message从MessageQueue中移除,如果没有消息就堵塞等待下一个消息到来;取出Message后调用Handler的dispatchMessage方法分发。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值