Handler源码分析

Handler源码分析

Activity启动时的Looper

当程序运行时,会先执行ActivityThreadmain方法。会执行Looper.prepareMainLooper()方法和Looper.loop()方法。

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

其中又会进入prepare方法中,会发现调用了sThreadLocal.set(new Looper(quitAllowed));其中通过new Looper()方法

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

对MessageQueue队列进行了初始化。
set方法:

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

将当前主线程添加到sThreadLocal中。通过static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>()设置静态实现保证其唯一性。

Looper.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;

首先通过myLooper()方法,

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

拿到存入的主线程的Looper对象值,然后再拿到MessageQueue对象,
其中

for (;;) {
            Message msg = queue.next(); // might block
            ......
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
           ......
        }

我们可以发现通过queue.next()拿到队列中先进先出的值,使用msg.target.dispatchMessage(msg);进行分发,其中msg.target为Handler(在Message类中我们可以找到Handler target的定义)。

子线程中Handler调用sendMessage发送数据

我们在子线程中通过handler1.sendMessageDelayed(message,3000);进行发送数据,最后都会调用到handler中的sendMessageAtTime()方法,

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
		//对MessageQueue进行赋值,并传入到enqueueMessage方法中
        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);
    }

然后调用enqueueMessage()方法,

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

在此方法中对Message的target属性进行了赋值。
然后通过MessageQueue类queue.enqueueMessage(msg, uptimeMillis)进行队列的填充。
其中主要代码为:

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;
            }

将定义的全局的mMessages拿到,进行非空判定,若为空则直接添加到队列首位。不为空,则通过链表的方式,将当前发送的Message对象添加到队列的尾部。实现数据的填充队列处理。

Handler的数据处理

Looper.loop()的源码中可以看到,在程序启动时,在主线程中loop()方法的for (;;)进行无限循环,通过Message msg = queue.next()取得队列中的首位Message消息对象,然后通过Handler的msg.target.dispatchMessage(msg)进行分发处理。

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

其中此时msg.callback为null,则进入

if (mCallback != null) {
   if (mCallback.handleMessage(msg)) {
       return;
   }
}
handleMessage(msg);

然后在我们的Activity中重写

private Handler handler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return true;
        }
    });

或者

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

来进行主线程中处理数据更新。

子线程中handler1.post()或者runOnUiThread可以更新UI的原因

其中runOnUiThread方法为

public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }

同样调用handler的post方法。
然后进入

public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }

调用sendMessageDelayed方法时,参数getPostMessage(r)为将post的Runnable方法赋值给Message。

private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

其中Message的callback属性为Runnable。然后同样调用到enqueueMessage()方法中,然后通过主线程中Loop.loop()的无限循环将其拿到,调用dispatchMessage方法,

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

此时msg.callback将不为null,将会进入handleCallback(msg);中,执行

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

run()方法进行主线程更新操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值