欢迎来到天天文库
浏览记录
ID:22579742
大小:145.04 KB
页数:14页
时间:2018-10-30
《优就业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.
8、.clearCallingldentityO;if(ident!=newldent){Log.
此文档下载收益归作者所有