Android应用程序消息处理机制(Looper、Handler)分析(4)
2. 消息的发送 应用程序的主线程准备就好消息队列并且进入到消息循环后,其它地方就可以往这个消息队列中发送消息了。我们继续以文章开始介绍的Android应用程序启动过程源代码分析一文中的应用程序启动过为例,说明应用程序是如何把消息加入到应用程序的消息队列中去的。 在Android应用程序启动过程源代码分析这篇文章的Step 30中,ActivityManagerService通过调用ApplicationThread类的scheduleLaunchActivity函数通知应用程序,它可以加载应用程序的默认Activity了,这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中: publicfinalclassActivityThread{ ...... privatefinalclassApplicationThreadextendsApplicationThreadNative{ ...... //weusetokentoidentifythisactivitywithouthavingtosendthe //activityitselfbacktotheactivitymanager.(mattersmorewithipc) publicfinalvoidscheduleLaunchActivity(Intentintent,IBindertoken,intident, ActivityInfoinfo,Bundlestate,List<ResultInfo>pendingResults, List<Intent>pendingNewIntents,booleannotResumed,booleanisForward){ ActivityClientRecordr=newActivityClientRecord(); r.token=token; r.ident=ident; r.intent=intent; r.activityInfo=info; r.state=state; r.pendingResults=pendingResults; r.pendingIntents=pendingNewIntents; r.startsNotResumed=notResumed; r.isForward=isForward; queueOrSendMessage(H.LAUNCH_ACTIVITY,r); } ...... } ...... } 这里把相关的参数都封装成一个ActivityClientRecord对象r,然后调用queueOrSendMessage函数来往应用程序的消息队列中加入一个新的消息(H.LAUNCH_ACTIVITY),这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中: publicfinalclassActivityThread{ ...... privatefinalclassApplicationThreadextendsApplicationThreadNative{ ...... //ifthethreadhasn'tstartedyet,wedon'thavethehandler,sojust //savethemessagesuntilwe'reready. privatefinalvoidqueueOrSendMessage(intwhat,Objectobj){ queueOrSendMessage(what,obj,0,0); } ...... privatefinalvoidqueueOrSendMessage(intwhat,Objectobj,intarg1,intarg2){ synchronized(this){ ...... Messagemsg=Message.obtain(); msg.what=what; msg.obj=obj; msg.arg1=arg1; msg.arg2=arg2; mH.sendMessage(msg); } } ...... } ...... } 在queueOrSendMessage函数中,又进一步把上面传进来的参数封装成一个Message对象msg,然后通过mH.sendMessage函数把这个消息对象msg加入到应用程序的消息队列中去。这里的mH是ActivityThread类的成员变量,它的类型为H,继承于Handler类,它定义在frameworks/base/core/java/android/app/ActivityThread.java文件中: publicfinalclassActivityThread{ ...... privatefinalclassHextendsHandler{ ...... publicvoidhandleMessage(Messagemsg){ ...... switch(msg.what){ ...... } ...... } ...... } 这个H类就是通过其成员函数handleMessage函数来处理消息的了,后面我们分析消息的处理过程时会看到。 本文转自 Luoshengyang 51CTO博客,原文链接:http://blog.51cto.com/shyluo/966600,如需转载请自行联系原作者