Handler系列—Message对象的获取机制,安卓kotlin面试题

}

return new Message();

}

可以看到,如何sPool对象为null,则new一个Message对象;如果不为空,就把sPool的第一个节点对象返回,然后把sPool指向下一个节点。那么sPool到底是什么呢???其实他就是一个Message链表,每个Message里都有一个next字段,类型也是Message对象。

到这里也看到了Message对象的获取方式分为两种情况

总结:

如果sPool为null,则直接通过new来获取

如果sPool不为null,则将sPool的第一个节点返回,然后把sPool指向其下一个节点

那么这里又有一个问题,sPool是什么时候生成和赋值的,什么时候向sPool池中添加Message对象的呢?接下来我们通过源码定位到了recycleUnchecked()这个方法,这个方法又是在recycle()方法中调用的

源码解析recycle()和recycleUnchecked()方法


public void recycle() {

//判断当前message是否可以被回收(是否正在被使用)

if (isInUse()) {

if (gCheckRecycle) {

throw new IllegalStateException("This message cannot be recycled because it "

  • “is still in use.”);

}

return;

}

//当前message对象可以被回收

recycleUnchecked();

}

void recycleUnchecked()
{

// Mark the message as in use while it remains in the recycled object pool.

// Clear out all other details.

//这些就是清除当前message对象的成员变量信息(相当于一个新的message)

flags = FLAG_IN_USE;

what = 0;

arg1 = 0;

arg2 = 0;

obj = null;

replyTo = null;

sendingUid = UID_NONE;

workSourceUid = UID_NONE;

when = 0;

target = null;

callback = null;

data = null;

synchronized (sPoolSync) {

//当前池中的size小于最大size,就为池中添加当前message

//MAX_POOL_SIZE 大小默认为50

if (sPoolSize < MAX_POOL_SIZE) {

//当前message作为sPool的第一个节点

next = sPool;

//再将当前message赋值给sPool

sPool = this;

sPoolSize++;

}

}

}

这两个方法的源码还是比较容易看懂的,基本总结就是当message对象被回收的时候,先清除其成员变量信息,然后将该对象作为sPool池的第一个节点添加到池中。

那么问题又来了,message对象什么时候被回收呢???咱们可以猜想一下,当message对象不用了之后被回收;那么在Android的消息机制中,是通过Looper.loop()方法从消息队列中取出消息进行处理,那么咱们就去这个方法里去寻找我们想要的答案

解析Looper.loop()


public static void loop() {

final Looper me = myLooper();

//首先判断Looper对象为空,则直接抛异常

if (me == null) {

throw new RuntimeException(“No Looper; Looper.prepare() wasn’t called on this thread.”);

//省略部分代码

//通过looper拿到消息队列

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 {

//将message对象交给hadler的dispatchMessage方法进行处理消息

msg.target.dispatchMessage(msg);

if (observer != null) {

sage indicates that the message queue is quitting.

return;

}

//省略部分代码

try {

//将message对象交给hadler的dispatchMessage方法进行处理消息

msg.target.dispatchMessage(msg);

if (observer != null) {

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值