Android异步消息阻塞,Android 异步消息分发机制

原标题:Android 异步消息分发机制

Android的消息机制

–主要是指 Handler 的运行机制 和 MessageQueue 、 looper 的工作过程。

MessageQueue

MessageQueue 消息队列,用来存储消息,虽然称为消息队列,但是它的存储结构是采用 单链表的数据结构来存储消息队列的。

包含两个操作插入(enqueueMessage) 和 读取(next)

enqueueMessage :往消息链表 中插入一条信息

next:从消息列表中读取一天消息,并将其从消息队列中移除,next方法是一个无限循环的方法,如果消息列表里没有消息,那么会一直阻塞在这里。

Looper

Looper 消息循环,用来处理消息。

Looper 会不停的从 MessageQueue 中查看是否有新的消息,如果有新消息就会立即处理

Looper.java

privateLooper(booleanquitAllowed){

mQueue = newMessageQueue(quitAllowed);

mThread = Thread.currentThread();

}

在 Looper 的构造方法会创建一个MessageQueue,消息队列,然后将当前线程的对象保存起来。

publicstatic@ Nullable Looper myLooper(){

returnsThreadLocal. get();

}

privatestaticvoidprepare(boolean quitAllowed){

if(sThreadLocal. get() != null) {

thrownewRuntimeException( "Only one Looper may be created per thread");

}

sThreadLocal. set( newLooper(quitAllowed));

}

问题 为什么Looper.prepare() 不能被调用两次?

答:因为每次调用 Looper.prepare() 的时候的都会判断 ThreadLocal是否已经存储当前的 Looper 对象,如果已经存在就会抛出异常。

/**

* Run the message queue in this thread. Be sure to call

* {@link#quit()} to end the loop.

*/

publicstaticvoidloop(){

finalLooper me = myLooper();

if(me == null) {

thrownewRuntimeException( "No Looper; Looper.prepare() wasn't called on this thread.");

}

finalMessageQueue queue = me.mQueue;

// Make sure the identity of this thread is that of the local process,

// and keep track of what that identity token actually is.

Binder.clearCallingIdentity();

finallongident = Binder.clearCallingIdentity();

for(;;) {

Message msg = queue.next(); // might block

if(msg == null) {

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

return;

}

// This must be in a local variable, in case a UI event sets the logger

finalPrinter logging = me.mLogging;

if(logging != null) {

logging.println( ">>>>> Dispatching to "+ msg.target + " "+

msg.callback + ": "+ msg.what);

}

finallongtraceTag = me.mTraceTag;

if(traceTag != 0&& Trace.isTagEnabled(traceTag)) {

Trace.traceBegin(traceTag, msg.target.getTraceName(msg));

}

try{

msg.target.dispatchMessage(msg);

} finally{

if(traceTag != 0) {

Trace.traceEnd(traceTag);

}

}

if(logging != null) {

logging.println( "<<<<< Finished to "+ msg.target + " "+ msg.callback);

}

// Make sure that during the course of dispatching the

// identity of the thread wasn't corrupted.

finallongnewIdent = Binder.clearCallingIdentity();

if(ident != newIdent) {

Log.wtf(TAG, "Thread identity changed from 0x"

+ Long.toHexString(ident) + " to 0x"

+ Long.toHexString(newIdent) + " while dispatching to "

+ msg.target.getClass().getName() + " "

+ msg.callback + " what="+ msg.what);

}

msg.recycleUnchecked();

}

}

loop 方法就是一个死循环,跳出死循环的方法,是 MessageQueue的 Next 方法为空,即queue.next() 为空。Looper 调用 quit 方法或者 quitSafely 方法,通知消息队列退出,会使 MessageQueue 的 next 方法 返回为空。

loop 调用 MessageQueue 的 next 方法获取新的消息,如果 没有消息,next 方法会一直阻塞在那里,导致 loop 方法也会一直阻塞在那里。 如果 next 方法返回了新的消息,Looper 就会处理新的消息,调用 msg.target.dispatchMessage(msg),msg.target 就是发送这条消息的 Handler 对象(Handler 中有讲解)。这样就把代码逻辑切换到指定线程去执行了。

3. ThreadLocal

线程内部的数据存储类, 通过它可以在指定的线程存储数据,而且存储后,只能在指定线程获取存储的数据,其他线程无法获取。

应用:当某些数据是以线程为作用域,并且不同线程具有不同数据

存在Looper中,并不是线程,作用是在每个线程中存储数据

问题:Handler内部是如何获取当前线程的 Looper 的?

Handler.java

publicHandler(Callback callback, boolean async){

if(FIND_POTENTIAL_LEAKS) {

final Class extends Handler> klass = getClass();

if((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&

(klass.getModifiers() & Modifier.STATIC) == 0) {

Log.w(TAG, "The following Handler class should be static or leaks might occur: "+

klass.getCanonicalName());

}

}

mLooper = Looper.myLooper();

if(mLooper == null) {

thrownewRuntimeException(

"Can't create handler inside thread that has not called Looper.prepare()");

}

mQueue = mLooper.mQueue;

mCallback = callback;

mAsynchronous = async;

}

答:Handler 通过 ThreadLocal 获取每个线程的 Looper. ThreadLocal 可以在不同线程中互不干扰的存储并提供数据。

在调用 Looper.prepare() 的时候 “sThreadLocal.set(new Looper(quitAllowed));” - 创建了一个 Looper 实例并将一个Looper的实例放入了ThreadLocal 存储。然后在 Handler 中 调用“mLooper = Looper.myLooper();”-从 sThreadLocal.get() 获取到 Looper 对象。

问题:主线程中为什么可以默认使用Handler?

答: 线程默认是没有Looper 的 ,如果要使用 Handler ,就必须为线程创建 Looper. 但是主线程,也就是 UI 线程,它就是 ActivityThread, ActivityThread 被创建的时候默认会初始化 Looper,当前UI线程调用了Looper.prepare()和Looper.loop()方法.

4. Handler

主要工作:发送和接收消息;

publicfinalbooleansendMessage(Message msg)

{

returnsendMessageDelayed(msg, 0);

}

publicfinalbooleansendMessageDelayed(Message msg, longdelayMillis)

{

if(delayMillis < 0) {

delayMillis = 0;

}

returnsendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);

}

publicbooleansendMessageAtTime(Message msg, longuptimeMillis){

MessageQueue queue = mQueue;

if(queue == null) {

RuntimeException e = newRuntimeException(

this+ " sendMessageAtTime() called with no mQueue");

Log.w( "Looper", e.getMessage(), e);

returnfalse;

}

returnenqueueMessage(queue, msg, uptimeMillis);

}

privatebooleanenqueueMessage(MessageQueue queue, Message msg, longuptimeMillis){

msg.target = this;

if(mAsynchronous) {

msg.setAsynchronous( true);

}

returnqueue.enqueueMessage(msg, uptimeMillis);

}

由上面可以看出 Handler 发送消息的过程就是向消息链表中插入了一条消息,MessageQueue 的 next 方法会返回这条消息给 Looper,Looper 收到消息,通过msg.target.dispatchMessage(msg) 交给 Handler 处理。

上面 enqueueMessage 方法首先 “msg.target = this;” 会把 this 赋值给 msg.target ,也就是说 把Handler 赋值给 msg的 target 属性。

publicvoiddispatchMessage(Message msg){

if(msg.callback != null) {

handleCallback(msg);

} else{

if(mCallback != null) {

if(mCallback.handleMessage(msg)) {

return;

}

}

handleMessage(msg);

}

}

首先会检查 Message的 callback 是否为 null,不为空就处理通过 handleCallback 来处理消息。

callback 是一个 Runnable 接口,就是 Handler 的 post 方法传递的 Runnable 参数

privatestaticvoidhandleCallback(Message message){

message.callback.run();

}

举个栗子 第一种handler 的使用方式,post方法

Handler mHandler = newhandler();

mHandler.post( newRunnable()

{

@Override

publicvoidrun()

{

Log.e( "TAG", Thread.currentThread().getName());

mTxt.setText( "yoxi");

}

});

其次 查看 mCallback 是否为空,mCallback 是个接口

publicinterfaceCallback{

publicbooleanhandleMessage(Message msg);

}

Callback 提供另一种使用 Handler 的方式,不想派生Handler的子类,可以通过 Callback 来实现。

举个栗子 第二种使用 Handler 的方式

privateHandler mHandler = newHandler()

{

publicvoidhandleMessage(android.os.Message msg)

{

switch(msg.what)

{

casevalue:

break;

default:

break;

}

};

};

最后,调用 Handler的 handleMessage 方法来处理消息。

责任编辑:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值