android开发hander机制详细介绍_第1页
android开发hander机制详细介绍_第2页
android开发hander机制详细介绍_第3页
android开发hander机制详细介绍_第4页
android开发hander机制详细介绍_第5页
已阅读5页,还剩12页未读, 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、android looper 和 handlermessage:消息,其中包含了消息id,消息处理对象以及处理的数据等,由 messagequeue 统一列队,终由 handler 处理。handler:处理者,负责message的发送及处理。使用handler时,需要实 现handlemessage(message msg)方法來对特定的message进彳亍处理,例如更 新ui等。messagequeue:消息队列,用来存放handler发送过来的消息,并按照fifo 规则执行。当然,存放message并非实际意义的保存,而是将message以 链表的方式串联起来的,等待looper的抽取。

2、looper:消息泵,不断地从messagequeue中抽取message执彳亍。因此,一 个 messagequeue 需要一个 looper。thread:线程,负责调度整个消息循环,即消息循环的执行场所。android系统的消息队列和消息循环都是针对具体线程的,一个线程可以存在(当然也可以不存在)一个消息队列和一个消息循环(looper),特定线程的消息只能分发给本线程,不能进行跨线程,跨进程通讯。但是创建的工作线程 默认是没有消息循环和消息队列的,如果想让该线程具有消息队列和消息循环, 需要在线程中首先调用looper.prepare。来创建消息队歹u,然后调用looper.loop(

3、) 进入消息循环。如下例所示:class looperthread extends thread public ilem dlcr ml la ndlcr;public void nm() looper, prepare (); 给线程创建一个消息循环 inhandler = new handler () public void handlemessage(message msg) / process incoming messages here;消息注:写在looper. loop()之后的代码不会被立即执行,当调用后 mhandler. getlooper (). quit ()后,loo

4、p才会中止,其后的代码才能得以运行。 looper 对象通过 mcssagcqueuc来存放消息和事件。一个线程只能冇一个looper,对应一个messagequeue。这样你的线程就具有了消息处理机制了,在handler中进行消息处理。activity是一个ui线程,运行于主线程中,android系统在启动的时候会为 activity创建一个消息队列和消息循环(looper)。详细实现请参考 activitythread. java 文件。android应用程序进程在启动的时候,会在进程中加载activitythread类,并 且执行这个类的main函数,应用程序的消息循环过程就是在这个ma

5、in函数里面 实现的public final class activitythread public static final void main(string args)looper.preparemai nlooper();activitythread thread 二 new activitythread(); thread, attach(false);looper, loop ();thread detacho ;这个函数做了两件事情,一是在主线程屮创建了一个activitythread实例,二 是通过looper类使主线程进入消息循环中,这里我们只关注后者。首先看looper.pr

6、eparemainlooper函数的实现,这是一个静态成员函数,定义 在 frameworks/base/core/java/android/os/looper.java 文件中:1 /looper类分析2 没找到合适的分析代码的办法,只能这么来了。毎个重要行的上面都会加 上注释3 /功能方面的代码会在代码前加上一段分析4 public class looper 5 /static变量,判断是否打印调试信息。6 private static final boolean debug = false;7 private static final boolean locallogv 二 debug

7、? config. logd :config. logv;89/ sthreadlocal. get() will return null unless you,ve called prepare().10 /线程本地存储功能的封装,tls, thread local storage,什么意思呢?因 为存储要么在栈上,例如函数内定义的内部变量。要么在堆上,例如new或者 malloc出來的东西。11 /但是现在的系统比如linux和windows都捉供了线程本地存储空间,也就 是这个存储空间是和线程相关的,一个线程内有一个内部存储空间,这样的话我 把线程相关的东西就存储到12 这个线程的tls

8、中,就不用放在堆上而进行同步操作了。 /threadlocal并不是一个thread,而是thread的局部变量。13 private static final threadlocal sthreadlocal = new threadloc al 0 ;14 /消息队列,messagequeue,看名字就知道是个queue.15 final messagequeue mqueue;16 volatile boolcan mrun;17 /和本looper相关的那个线程,初始化为null18 thread mthread;19 private printer mlogging二 null;20

9、 /static变量,代表一个ui process (也口j能是service吧,这里默认就 是ui)的主线程21 private static looper mmainlooper = null;2223public static final void prepare() if (sthreadlocal. get () != null) throw new runtimeexception("only one looper may be cr thread"); sthrcadloca1. set(new looper ();29 往tls中设上这个looper对象的,

10、如果这个线程已经设过了 looper的话 就会报错,这说明,一个线程只能设一个loopero/313233eated per343536 373843 由framework设置的ut程序的主消息循环,注意,这个主消息循环是不 会主动退出的444546474849505152535455/public static final void preparemainlooper() prepare ();setmai nlooper(mylooper();判断主消息循环是否能退出/通过quit函数向looper发出退出申请if (process. supportsprocesses() myloope

11、r(). mqueue. mquitallowed 二 false;private synchronized static void setmainlooper(looper looper)565758mmainlooper 二 looper; 5961 public synchronized static final looper getmainlooper() 62 return mmainlooper;63 646569 消息循环,整个程序就在这里wh订e 了。70 /这个是static函数喔!71 public static final void loop() 72 looper me

12、 = mylooper () ;/从该线程屮取出对应的looper对象73 messagequeue queue = me. mqueue;/取消息队列对象.74 wh订e (true) 75 message msg = queue, next () ; / might block 取消息队列 中的一个待处理消息76 /if (!me. mrun) /是否需要退lb? mrun 是个 volatile 变 量,跨线程同步的,应该是有地方设置它。7778798081i t message.828384858687888990919293949596/ break;/if (msg != null

13、) if (msg. target 二二 null) / no target is a magic identifier for the qu rcturn;if (me. mlogging!= null) me. mlogging. println(>>>>> dispatching to + msg. target + msg. callback + :+ msg. what);msg.target. dispatchmessage(msg);if (me. mlogging!二 null) me. mlogging. printin(,z<<&l

14、t;<< finished to " + msg. target + "+ msg. callback); msg. recycle ();97101 /返冋和线程相关的looper102 public static final looper mylooper() 103 rcturn (looper)sthrcadlocal. get();104 105 106115 /设置调试输出对象,looper循环的时候会打印相关信息,用來调试用最 好了。116 public void setmessagelogging(printer printer) 117 mlo

15、gging = printer;118 119120125 public static final messagequeue myqueue() 126 return mylooper(). mqueue;127 128129/创建一个新的looper对彖,/内部分配一个消息队列,设置mrun为trueprivate looper() mqueue = new messagequeue(); mrun 二 true;mthread = thread. currentthread();publ ic void qui t () message msg = message, obtain();/

16、note: by enqueueing directly into the message queue, t / message is left with a null target. this is how we kn/ a quit message. mqueue. enqueucmcssagc(msg, 0);public thread getthread() return mthread;后面就简单了,打卬,异常定义等。public void dump(printer pw, string prefix)pw. println(prefix +pw. println(prefix +p

17、w. printin(prefix +this);“mrun二 + mrun);"mthread二"+ mthread);pw. printin(prefix +"mqueue二 + (mqueue != null) ? mqueu(null");if (mqueue !二 nul1) synchronized (mqueue) message msg = mqueue. mmessages;int n = 0; while (msg !二 null) pw. printin(prefix + " message + n + :+n+;msg

18、= msg. next;pw. printin (pref ix + z,(total messages: + n + “)169170public string tostringo 171return "looper172+ tnteger.tohexstring(system, identityhashcode(this)173+ t;174175176static class handlerexception extends exception 177178hemdlerexcepti on(message message, throwable cause) 179super

19、(crcatcmessage(cause),cause);180181182static string createmessage(throwable cause) 183string causemsg = cause. getmessageo ;184if (causemsg 二二 nu11) 185causemsg = cause. tostringo ;186187return causemsg;188189190 那怎么往这个消息队列中发送消息呢? ?调用looper的static函数myqueue 可以获得消息队列,这样你就可用自己往里边插入消息了。不过这种方法比较麻 烦,这个时候h

20、andler类就发挥作用了。先來看看handler的代码,就明口了。1 class handler2 3 /handler默认构造函数4 publ ic handl er () 5 这个if是干嘛用的暂时还不明口,涉及到j3v3的深层次的内容了应该6 if (find_potent1al_leaks) 7 final class<? extends handler> klass = getclass ();8 if (klass. isanonymousclass () | | klass. ismemberclass () | | klass. islocalclass() &a

21、mp;&9 (klass. gctmodificrs () & modifier. static) = 0) 10 log. w(tag, "the following handler class should be static or leaks might occur: " +11 klass. getcanonicalname();12 13 14 /获取本线程的looper对象15 如果木线程述没有设置looper,这回抛异常mlooper = looper mylooper (); if (mlooper = null) throw new run

22、timeexception("can't create handler inside thread that has not c looper prepare () ”);16171819ailed2021 /无耻啊,直接把looper的queue和自己的queue搞成一个了22 /这样的话,我通过handler的封装机制加消息的话,就相当于直接加到了 1 ooper的消息队列中去了2324252627282930313233mqueue = mlooper .mqueue; mcallback = null;述有好几种构造函数,/由外部设置looper个是带callback

23、的,个是带looper的public ilemdlcr(looper looper) mlooper = looper;mqueue = looper. mqueue; mcallback 二 null;带 callback 的,一个 handler 可以设置一个 callback。如果有 callback/的话,34 /凡是发到通过这个handler发送的消息,都有callback处理,相当于一个 总的集中处理/待会看dispatchmessage的时候再分析public353637383940414243444546474849ilemdlcr(looper looper, callbac

24、k callback) mlooper = looper;mqueue = looper .niqueue;mcallback = callback;/通过handler发送消息/调用了 内部的一个 sendmessagedelayedpublic final boolean sendmessage(message msg)return sendmessagedelayed(msg, 0);/ft,又封装了一层,这凹是调用sendmessageattime 了/因为延时时间是基于当前调用时间的,所以需要获得绝对时间传递给sendmessageattime50 public final bool

25、ean sendmessagedelayed(message msg, long delaymi1 lis)51 52 if (delaymillis < 0) 53 delaymillis 二 0;5859606162636465666768697071);727374757677数787980818283848586seif (mcallback != null) if (mcallback. handlemessage(msg) return;54 55 return sendmessageattime(msg, systemclockuptimemillis() + delaym

26、illis);56 57 public boolean sendmessageattime(message msg, long uptimemillis)boolean sent 二 false;mcssagcqucuc queue = mqueue; if (queue != null) 把消息的target设置为自己,然后加入到消息队列中对于队列这种数据结构来说,操作比较简单了msg. target 二 this;sent = qucucmcssagc(msg, uptimemillis);else runtimeexception e 二 new runtimeexception(thi

27、s + " sendmessageattime() cal 1ed with no mqueuelog. w("looper", e. getmessage (), e); return sent;/还记得looper中的那个消息循环处理吗/从消息队列屮得到一个消息后,会调用它的target的dispatchmesage函/message的target已经设置为handler 了,所以/最后会转到handler的msg处理上来这里有个处理流程的问题 public void dispatchmcssagc(message msg) /如果msg本身设置了 callb

28、ack,则直接交给这个callback处理了if (msg. callback != null) handlecallback(msg); el/如果该handler的callback有的话,则交给这个callback处理了相当于集屮处理878889909192 /否则交给派主处理,基类默认处理是什么都不干93 handlemessage(msg);94 95 96 97 生成message msg = mhandler.obtainmessage(); msg.what = what;msg.s en dtotargetf);发送messagequeue queue = mqueue;if

29、(queue != null) msg.target = this;sent = queue.enqueuemessage(msg, uptimemillis);在 handler.java 的 sendmessageattime(message msg, long uptimemillis)方法中,我 们看到,它找到它所引用的messagequeue,然后将message的target设定成自 己(口的是为了在处理消息环节,message能找到正确的handler),再将这个 message纳入到消息队列中。抽取looper me = mylooperf);messagequeue queu

30、e = me.mqueue;while (true) message msg = queue.next(); / might block讦(msg != null) if (msg.target = null) / no target is a magic identifier for the quit message, return;msg.target.dispatchmessage(msg);msg.recycled;在looper.java的loop()函数里,我们看到,这里有一个死循环,不断地从messagequeue中获取下一个(next方法)message,然后通过message

31、中携带 的target信息,交曲正确的handler处理(dispatchmessage方法)。处理if (msg.callback != null) han dlecallback(msg); else if (mcallback 1= null) if (mcallback.handlemessage(msg) return;han dlemessage(msg);在handler.java的dispatchmessage(message msg)方法里,其中的一个分支就是调 用handlemessage方法来处理这条message,而这也正是我们在职责处描述使用 handler 时需要实

32、现 handlemessage(message msg)的原因。至于dispatchmessage方法小的另外一个分支,我将会在后而的内容小说明。 至此,我们看到,一个message经由handler的发送,messagequeue的入队, looper的抽取,乂再一次地冋到handler的怀抱。而绕的这一圈,也正好帮助我 们将同步操作变成了异步操作。handler的作用是把消息加入特定的(looper)消息队列中,并分发和 处理该消息队列中的消息。构造handler的时候可以指定一个looper 对象,如果不指定则利用当前线程的looper创建。详细实现请参考 looper的源码。一个act

33、ivity中可以创建多个工作线程或者其他的组件,如果这些线 程或者组件把他们的消息放入activity的主线程消息队列,那么该消 息就会在主线程屮处理了。因为主线程一般负责界面的更新操作,并且android 系统中的weget不是线程安全的,所以这种方式可以很好的实现 android 界面更新。在android系统中这种方式有着广泛的运用。那么另外一个线程怎样把消息放入主线程的消息队列呢?答案是通过 handle对象,只要handler对象以主线程的looper创建,那么调用handler的sendmessage等接口,将会把消息放入队列都将是放入主线程的消息队列。并一且将会在handler主

34、线程中调用该handler的handlcmessage接口来处理消息。3)剩下的部分,我们将讨论一下handler所处的线程及更新ui的方式。在主线程(ui线程)里,如果创建handler吋不传入looper对象,那么将直接 使用主线程(ui线程)的looper对象(系统已经帮我们创建了);在其它线程 里,如果创建handler时不传入looper对象,那么,这个handler将不能接收处 理消息。在这种情况下,通用的作法是:class looperthread extends thread public handler mhandler;public void run() looper.prepare();mhandler = new handler() public void handlemessage(message msg) / process incoming messages here;loopero op();在创建handler之前,为该线

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论