android消息管理是什么意思,Android消息处理机制4——Looper

Android消息处理机制系列文章整体内容如下

一 使用

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare in the thread that is to run the loop, and then loop to have it process messages until the loop is stopped.

翻译成中文是

Looper用于运行线程的消息循环,线程默认没有关联looper;如果要创建一个looper,先在线程内部调用prepare(),然后循环让它处理消息,直到线程停止。

looper具体使用的例子

class LooperThread extends Thread {

public Handler mHandler;

public void run() {

Looper.prepare();

mHandler = new Handler() {

public void handleMessage(Message msg) {

// process incoming messages here

}

};

Looper.loop();

}

}

Android也提供了一个关联looper的线程 HandlerThread

二 构造器

private Looper(boolean quitAllowed) {

mQueue = new MessageQueue(quitAllowed);

mThread = Thread.currentThread();

}

创建Looper实例的时候会同时创建一个MessageQueue,Looper只有一个私有的构造器,创建一个Looper实例只能通过

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是用ThreadLocal存储的,ThreadLocal存储的变量有一个特点,就是只能被同一个线程读写。

上面的代码的意思是,如果该线程已经绑定一个Looper实例,则抛出异常,否则就创建一个。

public static void prepareMainLooper()

主线程初始化的时候会调用prepareMainLooper来创建Looper实例

三 管理消息队列

使用loop()方法来管理消息队列,通过loop()方法循环从MessageQueue里面取出消息,然后给handler处理。loop()方法里调用for(;;)形成死循环,当前线程在loop方法之后的方法都不会执行。下面分析loop方法的源码

public static void loop() {

final Looper me = myLooper();

//代码省略

for (;;) {

Message msg = queue.next(); // 取出messageQueue头部的message,同时会把该message从messageQueue删除

if (msg == null) {

// No message indicates that the message queue is quitting.

return;

}

//代码省略

try {

msg.target.dispatchMessage(msg); //msg.target获取处理message的handler,其实就是发送该message的handler,然后调用该handler的dispatchMessage方法,将消息分发给该handler让其进行处理。

} finally {

if (traceTag != 0) {

Trace.traceEnd(traceTag);

}

}

//代码省略

msg.recycleUnchecked(); //将该msg初始化,并放入message池里面

}

}

loop()方法里做了三件事:

从messageQueue里面取出消息

将message分发给相应的handler,让handler处理

回收该message,将它放到消息池里面,消息池的数据结构是一个先进后出的链式栈

(完)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值