1.android消息机制-java

分析过,应用层消息机制 再来看看,后面继续扒一扒native

1 looper

//Looper.java 
public static void prepareMainLooper() {
    //1、创建不允许退出的Looper
    prepare(false);
    synchronized (Looper.class) {//保证只有一个线程执行
        if (sMainLooper != null) {
            throw new IllegalStateException("The main Looper has already 			been 		prepared.");
        }
        //2、将刚刚创建的Looper实例赋值给sMainLooper
        //sMainLooper字段是Looper类中专门为UI线程保留的,只要某个线程调用了prepareMainLooper方法,把它创建的Looper实例赋值给sMainLooper,它就可以成为UI线程,prepareMainLooper方法只允许执行一次
        sMainLooper = myLooper();
    }
}

private static void prepare(boolean quitAllowed){//quitAllowed表示是否允许Looper运行时退出
	//Looper.prepare()只能执行一次
	if (sThreadLocal.get() != null) {
		throw new RuntimeException("Only one Looper may be created per thread"); 
	 }
	//把Looper保存到TLS中
	sThreadLocal.set(new Looper(quitAllowed));
}

public static @Nullable Looper myLooper() {
	//获取当前线程TLS区域的Looper
	return sThreadLocal.get();
}

private static Looper sMainLooper;  // guarded by Looper.class
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

ThreadLocal:线程本地存储区(Thread Local Storage,简称为TLS),每 个线程都有自己的私有的本地存储区域,不同线程之间彼此不能访问对方的TLS区域。

它的常用操作方法有:
ThreadLocal.set(T value):将value存储到当前线程的TLS区域。
ThreadLocal.get():获取当前线程TLS区域的数据

public static Looper getMainLooper() {
    synchronized (Looper.class) {
        //返回UI线程的Looper实例
        return sMainLooper;
    }
}

UI线程的Looper的创建过程,执行ActivityThread.main后,应用程序就启动了,UI的消息循环也在Looper.loop方法中启动,此后Looper会一直从消息队列中取出消息,用户或系统通过Handler不断往消息队列中添加消息,这些消息不断的被取出,处理,回收,使得应用运转起来
我们在平时开发时,一般是使用不带参数的prepare()方法来创建子线程对应的Looper实例,如下:

//我们平时使用的prepare方法
public static void prepare() {
    //quitAllowed = true
    //UI线程的Looper是不允许推出的,而我们的Looper一般是允许退出的
    prepare(true);
}

2 MessageQueue

//Looper.java
final MessageQueue mQueue;
//Looper唯一的构造函数
private Looper(boolean quitAllowed) {
    //可以看到MessageQueue是在Looper中创建的
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}

MessageQueue是消息机制的核心类,它是java层和native层的连接纽带,它里面有大量的native方法,Android有俩套消息机制(java层和native层,实现不一样)

//MessageQueue.java  构造
private long mPtr; // used by native code
MessageQueue(boolean quitAllowed) {
    mQuitAllowed = quitAllowed;
    //通过native方法初始化消息队列,其中mPtr是供native代码使用
    mPtr = nativeInit();
}

每个线程最多只能对应一个Looper实例,而每个Looper内部只有一个MessageQueue实例,推出:每个线程最多对应一个MessageQueue实例。

3 .消息发送

public Handler(@Nullable Callback callback, boolean async) {
    //获取当前线程的Looper对象,后面分析
    mLooper = Looper.myLooper();
    //如果Looper为空会抛如下这个异常,这个异常相信Android初学者
    //遇见过很多次
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread " + Thread.currentThread()
            + " that has not called Looper.prepare()");
    }
    //获取当前线程Looper的MessageQueue
    mQueue = mLooper.mQueue;
    //Handler内部回调
    mCallback = callback;
    //注意这个mAsynchronous,是否是异步消息,后面分析
    mAsynchronous = async;
}

public final boolean sendMessage(@NonNull Message msg) {
        return sendMessageDelayed(msg, 0);
    }
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;//构造函数中由looper那里获取
        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代表处理此消息的Handler
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();
		//是否是异步消息,后面分析
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        //最终调用MessageQueue的enqueueMessage将此Message投递进MessageQueue
        return queue.enqueueMessage(msg, uptimeMillis);
    }
//MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
    //...
    synchronized (this) {
        //正在退出时,回收msg,加入到消息池
        if (mQuitting) {
            //...
            msg.recycle();
            return false;
        }
        msg.markInUse();
        msg.when = when;
        boolean needWake;
        //取mMessages链表头部的消息
        Message p = mMessages;
        //满足以下2种情况之一就把msg插入到链表头部:
        //1、如果p为null,则代表mMessages没有消息
        //2、如果when == 0 或 when < p.when, 则代表msg的触发时间是链表中最早的
        if (p == null || when == 0 || when < p.when) {
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;//如果处于阻塞状态,需要唤醒
        } else {//3、如果p != null且msg并不是最早触发的,就在链表中找一个位置把msg插进去
            //如果处于阻塞状态,并且链表头部是一个同步屏障,并且插入消息是最早的异步消息,需要唤醒
            needWake = mBlocked && p.target == null && msg.isAsynchronous();            
            Message prev;
            //下面是一个链表的插入操作, 将消息按时间顺序插入到mMessages中
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }  
                //如果在找到插入位置之前,发现了异步消息的存在,不需要唤醒
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p;
            prev.next = msg;
        }   
        
        //nativeWake方法会唤醒当前线程的MessageQueue
        if (needWake) {
            nativeWake(mPtr);
        }     
    }
    return true;
}

MessageQueue的enqueueMessage方法主要是一个链表的插入操作,返回true就代表插入成功,返回false就代表插入失败,它主要分为以下3种情况:

1、插入链表头部:

mMessages是按照Message触发时间的先后顺序排列的,越早触发的排得越前,头部的消息是将要最早触发的消息,当有消息需要加入mMessages时,如果mMessages为空或这个消息是最早触发的,就会直接插入链表头部;

2、插入链表的中间位置:

如果消息链表不为空并且插入的消息不是最早触发的,就会从链表头部开始遍历,直到找到消息应该插入的合适位置,以保证所有消息的时间顺序,这一个过程可以理解为插入排序;

3、判断是否调用nativeWake方法

最后,根据needWake是否为true,来决定是否调用nativeWake方法唤醒当前线程的MessageQueue,needWake默认为false,即不需要唤醒,needWake为true就代表此时处于以下2种情况:

(1)如果插入消息在链表头部并且mBlocked == true,表示此时nativePollOnce方法进入阻塞状态,等待被唤醒返回;

(2)如果插入消息在链表中间,消息链表的头部是一个同步屏障,同时插入的消息是链表中最早的异步消息,需要唤醒,即时处理异步消息。

4. looper 消息循环

// ActivityThread.java
public static void main(String[] args) {

    Looper.prepareMainLooper();
    .......
    ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    ......
    Looper.loop();
}
//Looper.java
public static void loop() {   
    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;
    //...
    for (;;) {
        //1、从MessageQueue中取出消息,没有消息时会阻塞等待
        Message msg = queue.next(); 
        //next()返回了null,表示MessageQueue正在退出,即调用了Looper的quit或quitSafely方法
        if (msg == null) {
            return;
        }
        //...
        //2、分发消息
        msg.target.dispatchMessage(msg);
        //...
        //3、回收消息
        msg.recycleUnchecked();
    }
}

loop()中是一个死循环,我们关注注释1,loop()会调用MessageQueue的next方法来获取最新的消息,当没有消息时,next()会一直阻塞在那里,这也导致loop()阻塞,唯一跳出循环的条件是next()返回null,这时代表Looper的quit()或quitSafely()被调用,从而调用MessageQueue的quit()来通知消息队列退出

//Looper.java
public void quit() {
    mQueue.quit(false);
}

//quitSafely和quit方法的区别是,quitSafely方法会等MessageQueue中所有的消息处理完后才退出,而quit会直接退出
public void quitSafely() {
    mQueue.quit(true);
}

//MessageQueue.java
Message next() {
    //mPtr是在构造中被赋值,是指向native层的MessageQueue
    final long ptr = mPtr;
    if (ptr == 0) {
        return null;
    }
    int pendingIdleHandlerCount = -1; 
    int nextPollTimeoutMillis = 0;
    //一个死循环,里面分为两部分,1、处理java层消息;2、如果没有消息处理,执行IdleHandler
    for(;;){
        //...
        //Part1:获取java层的消息处理
        //nativePollOnce方法用于处理native层消息,是一个阻塞操作
        //它在这两种情况下返回:1、等待nextPollTimeoutMillis时长后;2、MessageQueue被唤醒
        nativePollOnce(ptr, nextPollTimeoutMillis);
        synchronized (this) {
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            //mMessages是java层的消息队列,这里表示取出消息队列的第一个消息
            Message msg = mMessages;
            if (msg != null && msg.target == null) {//遇到同步屏障(target为null的消息)
                //在do-while中找到异步消息,优先处理异步消息
                //异步消息的isAsynchronous方法返回true
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {//有消息
                if (now < msg.when) { //消息还没到触发时间
                    //设置下一次轮询的超时时长(等待时长)
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {//now == msg.when, 消息到达触发时间
                    mBlocked = false;
                    //从mMessages的头部获取一条消息并返回 
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    //设置消息的使用状态,即flags |= FLAG_IN_US
                    msg.markInUse();
                    //返回这个消息
                    return msg;
                }
            } else {//msg == null,没有消息
                //设置nextPollTimeoutMillis为-1,准备进入阻塞,等待MessageQueue被唤醒
                nextPollTimeoutMillis = -1;
            }
            
            //调用了quit方法
            if (mQuitting) {
                dispose();
                return null;
            }
			
            //当处于以下2种情况时,就会执行到Part2:
            //1、mMessages == null,java层没有消息处理
            //2、now < msg.when,有消息处理,但是还没有到消息的执行时间
            //1、2两种情况都表明线程的消息队列处于空闲状态,处于空闲状态,就会执行IdleHandler
            
           //Part2:没有消息处理,执行IdleHandler
           //mIdleHandlers表示IdleHandler列表
           //pendingIdleHandlerCount表示需要执行的IdleHandler的数量
 
            if (pendingIdleHandlerCount < 0
                && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                //没有IdleHandler需要处理,可直接进入阻塞
                mBlocked = true;
                continue;
            }
		   //有IdleHandler需要处理
            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            //把mIdleHandlers列表转成mPendingIdleHandlers数组
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

        //遍历mPendingIdleHandlers数组
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            //取出IdleHandler
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler
            boolean keep = false;
            try {
                //执行IdleHandler的queueIdle方法,通过返回值由自己决定是否保持存活状态
                keep = idler.queueIdle();
            }
            //...省略异常处理
            
            if (!keep) {
                // 不需要存活,移除
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }
        
        //重置pendingIdleHandlerCount和nextPollTimeoutMillis为0
        pendingIdleHandlerCount = 0;
        //nextPollTimeoutMillis为0,表示下一次循环会马上从Messages中取出一个Message判断是否到达执行时间
        //因为IdleHandler在处理事件的时间里,有可能有新的消息发送来过来,需要重新检查
        nextPollTimeoutMillis = 0;
    }
}

MessageQueue的next方法有点长,但是它里面的逻辑是很好理解的,它主要是通过一个死循环不断的返回Message给Looper处理,next方法可以分为两部分阅读:

1、获取java层的消息处理:

我们看Part1,先执行nativePollOnce方法,它是一个阻塞操作,其中nextPollTimeoutMillis代表下一次等待的超时时长,当nextPollTimeoutMillis = 0时或到达nextPollTimeoutMillis时,它会立即返回;当nextPollTimeoutMillis = -1时,表示MessageQueue中没有消息,会一直等待下去,直到Hanlder往消息队列投递消息,执行nativeWake方法后,MessageQueue被唤醒,nativePollOnce就会返回,但它此时并不是立即返回,它会先处理完native层的消息后,再返回,然后获取java层的消息处理;

接着next方法就会从mMessages链表的表头中获取一个消息,首先判断它是否是同步屏障,同步屏障就是target为null的Message,如果遇到同步屏障,MessageQueue就会优先获取异步消息处理,异步消息就是优先级比同步消息高的消息,我们平时发送的就是同步消息,通过Message的**setAsynchronous(true)**可以把同步消息变成异步消息,不管是同步还是异步,都是Message,获取到Message后;

接着判断Message是否到达它的执行时间(if(now == msg.when)),如果到达了执行时间,next方法就会返回这条消息给Looper处理,并将其从单链表中删除;如果还没有到达执行时间,就设置nextPollTimeoutMillis为下一次等待超时时长,等待下次再次取出判断,可以发现虽然MessageQueue叫消息队列,但它却不是用队列实现的,而是用链表实现的。

通过MessageQueue的postSyncBarrier方法可以添加一个同步屏障,通过removeSyncBarrier方法可以移除相应的同步屏障,在Android,Choreographer机制中就使用到了异步消息,在View树绘制之前,会先往UI线程的MessageQueue添加一个同步屏障,拦截同步消息,然后发送一个异步消息,等待VSYN信号到来,触发View树绘制,这样就可以让绘制任务优先执行。
2、没有消息处理,遍历IdleHandler列表,执行IdleHandler的queueIdle方法:

IdleHandler是什么?IdleHandler是一个接口,它里面只有一个queueIdle方法,Idle是空闲的意思,在MessageQueue空闲的时候会执行IdleHandler的queueIdle方法,我们可以通过MessageQueue的addIdleHandler方法添加我们自定义的IdleHandler到mIdleHandlers列表中,如下:

//MessageQueue.java
private final ArrayList<IdleHandler> mIdleHandlers = new ArrayList<IdleHandler>(); 
public void addIdleHandler(@NonNull IdleHandler handler) {
    //...
    mIdleHandlers.add(handler);
}

MessageQueue空闲,就代表它处于以下两种情况:

(1) mMessages == null,消息队列中没有消息处理;

(2) now < msg.when,有消息处理,但是还没有到消息的执行时间.

以上两种情况之一都会触发next方法遍历IdleHandler列表,执行IdleHandler的queueIdle方法的操作

在Android中,我们平时所说的线程空闲其实就是指线程的MessageQueue空闲,这时就可以执行我们添加的IdleHandler,例如在LeakCanary中,它通过添加IdleHandler,在UI线程空闲时执行内存泄漏的判断逻辑.

5 消息分发

在消息循环的运行中,如果loop方法中MessageQueue的next方法返回了Message,那么就会执行到这一句:msg.target.dispatchMessage(msg);Looper会把这条消息交给该Message的target(Handler对象)来处理, 实际上是转了一圈,Handler把消息发送给MessageQueue,Looper又把这个消息给Handler处理,下面来看消息分发逻辑,dispatchMessage()源码如下:

//Handler.java
public void dispatchMessage(Message msg) {
    //1、检查msg的callback是否为空
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        //2、Handler的mCallback是否为空
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        //3、我们平常处理消息的方法,该方法默认为空,Handler子类通过覆写该方法来完成具体的逻辑。
        handleMessage(msg);
    }
}

//msg.callback其实是一个Runnable对象,当我们通过Handler来post一个Runnable消息时,它就不为空
//Handler.java
public final boolean post(Runnable r){
    return  sendMessageDelayed(getPostMessage(r), 0);
}
//把Runnable对象包装成Message对象
private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

//Handler.java
private static void handleCallback(Message message) {
    message.callback.run();
}

6 消息回收复用

1、消息的复用

//Message.java
public static Message obtain() {
        synchronized (sPoolSync) {
	    //从sPool头部取出一个Message对象返回,并把消息从链表断开(即把sPool指向下一个Message)
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0;//清除in-use flag
                sPoolSize--;//消息池的大小进行减1操作
                return m;
            }
        }
        //消息池中没有Message,直接new一个返回
        return new Message();
}

public final class Message implements Parcelable {
    public static final Object sPoolSync = new Object();//用于在获取Message对象时进行同步锁
    private static int sPoolSize = 0;//池的大小
    private static final int MAX_POOL_SIZE = 50;//池的可用大小
    private static Message sPool;
    Message next;
    //...
}

虽然叫消息池,其实是通过链表实现的,每个Message都有一个同类型的next字段,这个next就是指向下一个可用的Message,最后一个可用的Message的next为空,这样所有可用的Message对象就通过next串成一个Message池,sPool指向池中的第一个Message,复用消息其实是从链表的头部获取一个Message返回。

2、消息的回收
我们发现在obtain方法中新创建Message对象时,并不会直接把它放到池中再返回,那么Message对象是什么时候被放进消息池中的呢?是在回收Message时把它放入池中,Message中也有类似Bitmap那样的recycler函数,如下:

//Message.java
public void recycle() {
	//判断消息是否正在使用
        if (isInUse()) {
            if (gCheckRecycle) {//Android 5.0以后的版本默认为true,之前的版本默认为false.
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }
    
 //对于不再使用的消息,加入到消息池
 void recycleUnchecked() {
	 //将消息标示位置为IN_USE,并清空消息所有的参数
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
        synchronized (sPoolSync) {
           //当消息池没有满时,将Message对象加入消息池(即把Message插入链表头部)
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;//消息池的可用大小进行加1操作
            }
        }
    }

6 handler异步消息

最后我们再来看看异步消息,在Android源码绘制流程中使用了异步消息,目的是尽可能快的完成View的绘制

//ViewRootImpl.java
void scheduleTraversals() {
    ......
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
    .....
        mChoreographer.postCallback(
        Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
    ......
}
//Choreographer.java
public void postCallback(int callbackType, Runnable action, Object token) {
    postCallbackDelayed(callbackType, action, token, 0);
}
public void postCallbackDelayed(int callbackType,
                                Runnable action, Object token, long delayMillis) {
    ......
        postCallbackDelayedInternal(callbackType, action, token, delayMillis);
}

private void postCallbackDelayedInternal(int callbackType,
                                         Object action, Object token, long delayMillis) {
    ......
        synchronized (mLock) {
        .....
            Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action);
        msg.arg1 = callbackType;
        msg.setAsynchronous(true);
        mHandler.sendMessageAtTime(msg, dueTime);
    }
}
}


先调用postSyncBarrier开启同步屏障,屏蔽同步消息,接着设置setAsynchronous为true,将此消息设置为异步,则优先处理异步消息

6 同步屏障原理

我们从handler投递msg的分析知道,无论那种投递方式,只要是通过handler的sendXXX方法,最终一定会调用到enqueueMessage方法,

//Handler.java
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);
}

此方法第一行代码要做的事就是msg.target = this,而从MessageQueue.next方法中,我们知道要优先处理异步消息有两个条件,一是**(msg != null && msg.target == null),然后才循环消息链表,找到msg.isAsynchronous()为true的msg**,

//MessageQueue.java
Message next() {
	......
		for (;;) {
				if (msg != null && msg.target == null) {
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
			}
	......
}

我们可以得出结论,同步屏障就是向MessageQueue投递一个handler为空的msg,有了这个msg,从此msg开始,之后的所有同步消息都会被屏蔽,只会处理isAsynchronous为true的异步消息

//Message.java
//设置FLAG_ASYNCHRONOUS标示此msg为异步消息
public void setAsynchronous(boolean async) {
    if (async) {
        flags |= FLAG_ASYNCHRONOUS;
    } else {
        flags &= ~FLAG_ASYNCHRONOUS;
    }
}

//开启同步屏障:MessageQueue.java
public int postSyncBarrier() {
    return postSyncBarrier(SystemClock.uptimeMillis());
}

private int postSyncBarrier(long when) {

    synchronized (this) {
        final int token = mNextBarrierToken++;
        //创建没有handler的msg
        final Message msg = Message.obtain();
        msg.markInUse();
        //时间是当前系统时间
        msg.when = when;
        msg.arg1 = token;

        Message prev = null;
        Message p = mMessages;
        if (when != 0) {
            //找到晚于当前时间的msg
            while (p != null && p.when <= when) {
                prev = p;
                p = p.next;
            }
        }
        //将新创建的handler为空的msg插入到prev后面
        if (prev != null) { // invariant: p == prev.next
            msg.next = p;
            prev.next = msg;
        } else {
            //说明msg应该插到消息头部
            msg.next = p;
            mMessages = msg;
        }
        return token;
    }
}

我们总结下使用异步消息,两个条件:

  1. 开启同步屏障即投递一个handler为空的msg
  2. 将需要发送的msg设置为异步即调用setAsynchronous(true)

同步屏障只能屏蔽消息链表中添加空handler的msg之后的同步消息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 消息机制Android 系统中用于实现组件之间通信的重要机制之一。它允许不同组件之间通过消息进行异步通信,从而实现解耦和灵活性。 Android 消息机制主要通过以下几个核心类和接口来实现: 1. Handler:它是负责发送和处理消息的类。每个 Handler 都关联一个特定的 Looper 对象,用于处理消息队列。 2. Looper:它是一个线程的消息循环器,用于不断地从消息队列中获取消息并交给对应的 Handler 处理。 3. Message:它是消息的载体,包含了要传递的数据和标识信息。 4. MessageQueue:它是消息队列,用于存储待处理的消息。 5. Runnable:它是一个接口,用于定义需要在特定时刻执行的任务。 使用消息机制可以实现不同组件之间的通信,比如在一个子线程中执行耗时操作后,可以通过 Handler 发送消息到主线程,然后由主线程的 Handler 处理该消息并更新 UI。 以下是一个简单的示例代码,演示了通过消息机制在子线程和主线程之间进行通信: ```java // 在子线程中发送消息 Thread thread = new Thread(new Runnable() { @Override public void run() { // 创建一个 Handler 对象关联当前线程的 Looper Handler handler = new Handler(Looper.myLooper()); // 创建一个消息对象 Message message = Message.obtain(); message.what = 1; message.obj = "Hello from sub thread!"; // 发送消息 handler.sendMessage(message); } }); thread.start(); // 在主线程中处理消息 Handler mainHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { if (msg.what == 1) { String text = (String) msg.obj; // 在主线程中更新 UI textView.setText(text); } } }; ``` 这段代码中,子线程通过创建一个 Handler 对象关联当前线程的 Looper,并使用 sendMessage() 方法发送消息。在主线程中,我们使用主线程的 Looper 创建了一个 Handler 对象,并通过重写 handleMessage() 方法处理收到的消息。 这只是一个简单示例,Android 消息机制还可以用于更复杂的场景,比如在不同组件之间进行通信、定时任务的调度等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值