Android之浅谈:带你手撕Handler来了解handler原理_android handler 是你发给哪个 handler ,你就调用哪个hanlder

}
//发送消息
public void sendMessage(Message message){
   message.target=this;
   mQueue.enqueueMessage(message);
}

//处理消息
public void handleMessage(Message message) {
}
}


##### 2、实现Looper


我们以Looper.myLooper()作为入口看下Looper的源码



/\*\* Initialize the current thread as a looper.

* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
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));
}
/\*\*

* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}


可以看的出如果要获得looper最终是要调prepare(boolean quitAllowed)这个函数,这里再次证明一个线程只能创建一个looper,这里就会有小伙伴问我在主线程明明没有调用Looper.prepare啊,其实在主线程ActivityThread已经自动帮我创建了,所以在其他线程需要Looper的话均需要手动调用Looper.prepare();


那Looper又是怎么作为消息泵,并且将消息传递给handler呢?我们来看Looper.loop的源码(有剪切)



/\*\*

* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the 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;


for (;😉 {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
try {
msg.target.dispatchMessage(msg);

}


可以看得出来Looper的消息轮询是一个死循环,且不断的调用 Message msg = queue.next() 从MessageQueue取消息,然后调用 msg.target.dispatchMessage(msg);这里的target即handler,这样将消息传递给handler了;


这里我们模仿源码实现简易Looper



public class Looper {
//用于存放在该线程中的looper,确保一条线程只有一个looper,
//当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
//所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本
private static final ThreadLocal sThreadLocal = new ThreadLocal<>();
MessageQueue mQueue;

 private Looper(){
     mQueue =new MessageQueue();
 }
public static Looper myLooper(){
    return sThreadLocal.get();
}
public static void prepare(){
     if (null!=sThreadLocal.get()){
         throw new RuntimeException("Only one Looper may be created per thread");
     }
     sThreadLocal.set(new Looper());
}

public static void loop(){
     Looper looper=myLooper();
     if (looper==null){
         throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
     }
     MessageQueue queue=looper.mQueue;
     for (;;){
         Message next=queue.next();
         if (next==null||next.target==null){
             continue;
         }
         next.target.handleMessage(next);
     }
}
public void quit(){
     mQueue.quit();
}

}


##### 3、实现MessageQueue


我就以上述queue.nxet()为切入点进入源码看一下



Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;😉 {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}

        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;
            }
                // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }

            // If first time idle, then get the number of idlers to run.
            // Idle handles only run if the queue is empty or if the first message
            // in the queue (possibly a barrier) is due to be handled in the future.
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                // No idle handlers to run. Loop and wait some more.
                mBlocked = true;
                continue;
            }

            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }

        // Run the idle handlers.
        // We only ever reach this code block during the first iteration.
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler

            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }

            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }

        // Reset the idle handler count to 0 so we do not run them again.
        pendingIdleHandlerCount = 0;

        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }

这里看似很繁琐,其实可以大致流程为 nativePollOnce(ptr, nextPollTimeoutMillis);执行Native的消息机制,该方法会一直等待Native消息,其中 timeOutMillis参数为超时等待时间。如果为-1,则表示无限等待,直到有事件发生为止。如果值为0,则无需等待立即返回,所以主线程一直轮询是不会一直消耗cpu性能的,也不会造成卡顿,因为一有消息就会被唤醒。如果想进一步了解native消息机制可以看[深入理解Java Binder和MessageQueue]( )  
 接下来就是看 if (msg != null && msg.target == null) 是否有屏障消息,如果有就过滤掉同步消息直接执行就近的异步消息,代码再往下看就是时间是否到了消息等待的时候,到了则返回,接着往下看,这里涉及到空闲任务,当没有消息的时候,会执行一些空闲任务,例如GC,空闲任务执行完后nextPollTimeoutMillis又会重新置为0。


那MessageQueue里是怎么存消息的呢,当调用Handler发送消息的时候,不管是调用sendMessage,sendEmptyMessage,sendMessageDelayed还是其他发送一系列方法。最终都会调用 sendMessageAtTime(Message msg, long uptimeMillis),然而这个方法最后会调用enqueueMessage(Message msg, long when)。



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


boolean enqueueMessage(Message msg, long when) {
…省略
synchronized (this) {
…省略
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don’t have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
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;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}


消息队列里没有消息或者无需等待、小于消息头的等待时间的时候直接将消息放在头部,否则将消息插入合适的位置(比较等待时间),如果触发needWake那么就会直接唤醒native的消息,这里的mptr是NativeMessageQueue对象然后返回的地址。


这里我们模仿实现简易MessageQueue



public class MessageQueue {
//消息链表
Message mMessage;
private boolean isQuit;
public void enqueueMessage(Message message){
synchronized (this){
if (isQuit){
return;
}
Message p=mMessage;
if (nullp){
mMessage=message;
}else {
Message prev;
for (;😉{
prev =p;
p=p.next;
if (null
p){
break;
}
}
prev.next=message;
}
notify();//唤醒,模拟 nativeWake(mPtr);
}
}
public Message next(){
synchronized (this){
Message message;
for (;😉{
if (isQuit){
return null;
}
message=mMessage;
if (null!=message){
break;
}try {
wait(); //等待唤醒 模拟 nativePollOnce(ptr, nextPollTimeoutMillis);
}catch (InterruptedException e ){
e.printStackTrace();
}
}
mMessage=mMessage.next;
return message;
}
}
public void quit(){
synchronized (this){
isQuit=true;
Message message=this.mMessage;
while (null!=message){
Message next=message.next;
message.recycle();
message=next;
}
notify();
}
}
}


##### 4、实现Message


Message部分源码



/\*package\*/ Handler target;

/\*package\*/ Runnable callback;

// sometimes we store linked lists of these things
/\*package\*/ Message next;

/**
* Return a new Message instance from the global pool. Allows us to
* avoid allocating new objects in many cases.
*/
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize–;
return m;
}
}
return new Message();
}


这里的target就是handler这样就可以同过message.target.handlMessage() 去让handler处理消息了,这里还有一个next,这样他在messageQueue里就可以产生一个消息的单向链表。这里还有一个变量池,有兴趣的小伙伴可以自行去了解下message的复用


这里我们模仿实现简易Message



public class Message {
int what;
Object object;
Message next;
Handler target;
public void recycle(){
object=null;
next=null;
target=null;
}
}


这次我们分析和模拟handler机制算是完成了,让我们来看一下效果吧。



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Looper.prepare(); //手动调用我们自己prepare方法
final Handler handler=new Handler(){
@Override
public void handleMessage(Message message) { //处理消息
Log.i(“info1”, "handleMessage: "+message.what);
}
};
new Thread() {
@Override
public void run() {
Message message=new Message();
message.what=45;
handler.sendMessage(message); //子线程里发送消息
}
}.start();
Looper.loop(); //开启轮询
}



> 
> 链接;https://www.jianshu.com/p/fefd613893d7  
>  作者:是takiku啊
> 
> 
> 


**如果你想要深入系统的学习Android Framework框架,这里可以分享一份《Android Framework源码开发揭秘》,其中记录了从系统启动流程到WMS全部源码解析,相信你能优秀地学习整个Framework框架。**



> 
> 因文章篇幅原因,只放了部分内容,完整版**扫码免费领取!!**
> 
> 
> 


![](https://img-blog.csdnimg.cn/img_convert/d4ba40b0e0746c9823c449ef42920153.png)
### 第一章 系统启动流程分析


* 第一节 Android启动概览
* 第二节 init.rc解析
* 第三节 Zygote
* 第四节 面试题


![在这里插入图片描述](https://img-blog.csdnimg.cn/5fe36ad1311144cfa6b7f17b4949c836.png#pic_center)


### 第二章 跨进程通信IPC解析


* 第一节 Sercice 还可以这么理解
* 第二节 Binder基础
* 第三节 Binder应用
* 第四节 AIDL应用(上)
* 第五节 AIDL应用(下)
* 第六节 Messenger原理及应用
* 第七节 服务端回调
* 第八节 获取服务(IBinder)
* 第九节 Binder面试题全解析


![在这里插入图片描述](https://img-blog.csdnimg.cn/caf96b2bd50544769260112224c57f00.png#pic_center)


### 第三章 Handler源码解析


* 第一节 源码分析
* 第二节 难点问题
* 第三节 Handler常问面试题
* ![在这里插入图片描述](https://img-blog.csdnimg.cn/3b8b5aa9efe94683b585bde1ce1b1fe9.png#pic_center)


### 第四章 AMS源码解析


* 第一节 引言
* 第二节 Android架构
* 第三节 通信方式
* 第四节 系统启动系列
* 第五节 AMS
* 第六节 AMS 面试题解析


![在这里插入图片描述](https://img-blog.csdnimg.cn/2aa3f0c0eb32431793dac778d27a2c51.png#pic_center)


### 第五章 WMS源码解析


* 第一节 WMS与activity启动流程
* 第二节 WMS绘制原理
* 第三节 WMS角色与实例化过程
* 第四节 WMS工作原理


![在这里插入图片描述](https://img-blog.csdnimg.cn/1abeeff9d98a426b86b412fb844d5df6.png#pic_center)


### 第六章 Surface源码解析


* 第一节 创建流程及软硬件绘制
* 第二节 双缓冲及SurfaceView解析
* 第三节 Android图形系统综述
* ![在这里插入图片描述](https://img-blog.csdnimg.cn/56e3083053524a1b9b26d346323ce24a.png#pic_center)


### 第七章 基于Android12.0的SurfaceFlinger源码解析


* 第一节 应用建立和SurfaceFlinger的沟通的桥梁
* 第二节 SurfaceFlinger的启动和消息队列处理机制
* 第三节 SurfaceFlinger 之 VSync(上)
a3f0c0eb32431793dac778d27a2c51.png#pic_center)


### 第五章 WMS源码解析


* 第一节 WMS与activity启动流程
* 第二节 WMS绘制原理
* 第三节 WMS角色与实例化过程
* 第四节 WMS工作原理


![在这里插入图片描述](https://img-blog.csdnimg.cn/1abeeff9d98a426b86b412fb844d5df6.png#pic_center)


### 第六章 Surface源码解析


* 第一节 创建流程及软硬件绘制
* 第二节 双缓冲及SurfaceView解析
* 第三节 Android图形系统综述
* ![在这里插入图片描述](https://img-blog.csdnimg.cn/56e3083053524a1b9b26d346323ce24a.png#pic_center)


### 第七章 基于Android12.0的SurfaceFlinger源码解析


* 第一节 应用建立和SurfaceFlinger的沟通的桥梁
* 第二节 SurfaceFlinger的启动和消息队列处理机制
* 第三节 SurfaceFlinger 之 VSync(上)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值