优就业android教程-深入理解android异步消息处理机制

优就业android教程-深入理解android异步消息处理机制

ID:22579742

大小:145.04 KB

页数:14页

时间:2018-10-30

优就业android教程-深入理解android异步消息处理机制_第1页
优就业android教程-深入理解android异步消息处理机制_第2页
优就业android教程-深入理解android异步消息处理机制_第3页
优就业android教程-深入理解android异步消息处理机制_第4页
优就业android教程-深入理解android异步消息处理机制_第5页
资源描述:

《优就业android教程-深入理解android异步消息处理机制》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库

1、优就业Android教程-深入理解Android异步消息处理机制-、概述Android中的异步消息处理主要分为!U个咅P分组成,Message、Hndler、MessageQueue和Looper。其关系如下所示:MessageQueuenextnextMessageMessageMessagexte1.Message是线程之间传递的消息,它可以在内部携带少量信息,用于在不同线程之间交换数据2.MessageQueue是消息队列,它主要用于存放所有由Handler发送过来的消息,这部分消息会一直在消息队列中,等待被处理。每个线程中只会有一个Messag

2、eQueue对象。2.Handler是处理者,它主要用于发送和处理消息。发送消息一般使用handler的sendMessage()方法,处理消息会调用handleMessage()方法。3.Looper是每个线程中MessageQueue的管家,调用loop()方法后,就会进入到一个无限循环当中,然后每当发现MessageQueue中存在一条消息,就会将其取出,并传递到handleMessage()方法当中。每个线程中也只会有一个Looper对象。二、详细介绍1、Looper对于Looper主要是prepare()和loop()两个方法。publics

3、taticfinalvoidprepareO{if(sThreadLocal.getO!=null){thrownewRuntimeException("OnlyoneLoopermaybecreatedperthread");sThreadLocal.set(newLooper(true));}sThreadLocal是一个ThreadLocal对象,可以在一个线程中存储变量。Looper就是存储在sThreadLocal里面。这个方法被调用后,首先会判断当前线程里面有没有Looper对象,如果没有就会创建一个Looper对象,如果存在则会抛出异常。

4、可见,prepare()方法,不能被调用两次。这就保证了一个线程只有一个Looper对象。接下来我们看一下Looper的构造函数:privateLooper(booleanquitAllowed){mQueue=newMessageQueue(quitAllowed);mRun=true;mThread=Thread.currentThread();在Looper的构造函数中,创建了MessageQueue对象,这也保证了一个线程只有一个MessageQueue对象。然后我们看看loop()方法:publicstaticvoidloop(){final

5、Looperme=myLooper();if(me==null){thrownewRuntimeException(”NoLooper;Looper.prepare()wasn'tcalledonthisthread.");}finalMessageQueuequeue=me.mQueue;//Makesuretheidentityofthisthreadisthatofthelocalprocess,//andkeeptrackofwhatthatidentitytokenactuallyis.Binder.clearCallingldentityO

6、;finallongident=Binder.clearCallingldentityO;for(;;){Messagemsg=queue.next();//mightblockif(msg==null){//Nomessageindicatesthatthemessagequeueisquitting.return;}//Thismustbeinalocalvariable,incaseaUIeventsetstheIoggerPrinterlogging=me.mLogging;if(logging!=null){logging.println("

7、>>>>>Dispatchingto"+msg.target+""+msg.callback+":"+msg.what);msg.target.dispatchMessage(msg);if(logging!=null){logging.println("<<<<

8、.clearCallingldentityO;if(ident!=newldent){Log.

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。