Android中的Looper类&Handler &Message
16lz
2022-06-24
Android中的Looper类,是用来封装消息循环和消息队列的一个类,用于在android线程中进行消息处理。handler其实可以看做是一个工具类,用来向消息队列中插入消息的。
(1) Looper类用来为一个线程开启一个消息循环。
默认情况下android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环。)
Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。
(2) 通常是通过Handler对象来与Looper进行交互的。Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。
默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,Handler在主线程中定义,那么它是与主线程的Looper绑定。
mainHandler = new Handler() 等价于new Handler(Looper.myLooper()).
Looper.myLooper():获取当前进程的looper对象,类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。
(3) 在非主线程中直接new Handler() 会报如下的错误:
E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。
(4) Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。
注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。
(5) 基于以上知识,可实现主线程给子线程(非主线程)发送消息。
把下面例子中的mHandler声明成类成员,在主线程通过mHandler发送消息即可。
Android官方文档中Looper的介绍:
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.
This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.
(1) Looper类用来为一个线程开启一个消息循环。
默认情况下android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环。)
Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。
(2) 通常是通过Handler对象来与Looper进行交互的。Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。
默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,Handler在主线程中定义,那么它是与主线程的Looper绑定。
mainHandler = new Handler() 等价于new Handler(Looper.myLooper()).
Looper.myLooper():获取当前进程的looper对象,类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。
(3) 在非主线程中直接new Handler() 会报如下的错误:
E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。
(4) Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。
注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。
(5) 基于以上知识,可实现主线程给子线程(非主线程)发送消息。
把下面例子中的mHandler声明成类成员,在主线程通过mHandler发送消息即可。
Android官方文档中Looper的介绍:
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
Most interaction with a message loop is through the Handler class.
This is a typical example of the implementation of a Looper thread, using the separation of prepare() and loop() to create an initial Handler to communicate with the Looper.
01 | class LooperThread extends Thread { |
02 |
public Handler mHandler; |
03 |
|
04 |
public void run() { |
05 |
Looper.prepare(); |
06 |
|
07 |
mHandler = new Handler() { |
08 |
public void handleMessage(Message msg) { |
09 |
// process incoming messages here |
10 |
} |
11 |
}; |
12 |
|
13 |
Looper.loop(); |
14 |
} |
15 | } |
转自:http://vinny-w.iteye.com/blog/1334641
下文转自:http://blog.csdn.net/innost/article/details/6055793
[cpp]view plaincopy
- //Looper类分析
- //没找到合适的分析代码的办法,只能这么来了。每个重要行的上面都会加上注释
- //功能方面的代码会在代码前加上一段分析
- publicclassLooper{
- //static变量,判断是否打印调试信息。
- privatestaticfinalbooleanDEBUG=false;
- privatestaticfinalbooleanlocalLOGV=DEBUG?Config.LOGD:Config.LOGV;
- //sThreadLocal.get()willreturnnullunlessyou'vecalledprepare().
- //线程本地存储功能的封装,TLS,threadlocalstorage,什么意思呢?因为存储要么在栈上,例如函数内定义的内部变量。要么在堆上,例如new或者malloc出来的东西
- //但是现在的系统比如Linux和windows都提供了线程本地存储空间,也就是这个存储空间是和线程相关的,一个线程内有一个内部存储空间,这样的话我把线程相关的东西就存储到
- //这个线程的TLS中,就不用放在堆上而进行同步操作了。
- privatestaticfinalThreadLocalsThreadLocal=newThreadLocal();
- //消息队列,MessageQueue,看名字就知道是个queue..
- finalMessageQueuemQueue;
- volatilebooleanmRun;
- //和本looper相关的那个线程,初始化为null
- ThreadmThread;
- privatePrintermLogging=null;
- //static变量,代表一个UIProcess(也可能是service吧,这里默认就是UI)的主线程
- privatestaticLoopermMainLooper=null;
- /**Initializethecurrentthreadasalooper.
- *Thisgivesyouachancetocreatehandlersthatthenreference
- *thislooper,beforeactuallystartingtheloop.Besuretocall
- *{@link#loop()}aftercallingthismethod,andenditbycalling
- *{@link#quit()}.
- */
- //往TLS中设上这个Looper对象的,如果这个线程已经设过了looper的话就会报错
- //这说明,一个线程只能设一个looper
- publicstaticfinalvoidprepare(){
- if(sThreadLocal.get()!=null){
- thrownewRuntimeException("OnlyoneLoopermaybecreatedperthread");
- }
- sThreadLocal.set(newLooper());
- }
- /**Initializethecurrentthreadasalooper,markingitasanapplication'smain
- *looper.ThemainlooperforyourapplicationiscreatedbytheAndroidenvironment,
- *soyoushouldneverneedtocallthisfunctionyourself.
- *{@link#prepare()}
- */
- //由framework设置的UI程序的主消息循环,注意,这个主消息循环是不会主动退出的
- //
- publicstaticfinalvoidprepareMainLooper(){
- prepare();
- setMainLooper(myLooper());
- //判断主消息循环是否能退出....
- //通过quit函数向looper发出退出申请
- if(Process.supportsProcesses()){
- myLooper().mQueue.mQuitAllowed=false;
- }
- }
- privatesynchronizedstaticvoidsetMainLooper(Looperlooper){
- mMainLooper=looper;
- }
- /**Returnstheapplication'smainlooper,whichlivesinthemainthreadoftheapplication.
- */
- publicsynchronizedstaticfinalLoopergetMainLooper(){
- returnmMainLooper;
- }
- /**
- *Runthemessagequeueinthisthread.Besuretocall
- *{@link#quit()}toendtheloop.
- */
- //消息循环,整个程序就在这里while了。
- //这个是static函数喔!
- publicstaticfinalvoidloop(){
- Looperme=myLooper();//从该线程中取出对应的looper对象
- MessageQueuequeue=me.mQueue;//取消息队列对象...
- while(true){
- Messagemsg=queue.next();//mightblock取消息队列中的一个待处理消息..
- //if(!me.mRun){//是否需要退出?mRun是个volatile变量,跨线程同步的,应该是有地方设置它。
- //break;
- //}
- if(msg!=null){
- if(msg.target==null){
- //Notargetisamagicidentifierforthequitmessage.
- return;
- }
- if(me.mLogging!=null)me.mLogging.println(
- ">>>>>Dispatchingto"+msg.target+""
- +msg.callback+":"+msg.what
- );
- msg.target.dispatchMessage(msg);
- if(me.mLogging!=null)me.mLogging.println(
- "<<<<<Finishedto"+msg.target+""
- +msg.callback);
- msg.recycle();
- }
- }
- }
- /**
- *ReturntheLooperobjectassociatedwiththecurrentthread.Returns
- *nullifthecallingthreadisnotassociatedwithaLooper.
- */
- //返回和线程相关的looper
- publicstaticfinalLoopermyLooper(){
- return(Looper)sThreadLocal.get();
- }
- /**
- *ControlloggingofmessagesastheyareprocessedbythisLooper.If
- *enabled,alogmessagewillbewrittento<var>printer</var>
- *atthebeginningandendingofeachmessagedispatch,identifyingthe
- *targetHandlerandmessagecontents.
- *
- *@paramprinterAPrinterobjectthatwillreceivelogmessages,or
- *nulltodisablemessagelogging.
- */
- //设置调试输出对象,looper循环的时候会打印相关信息,用来调试用最好了。
- publicvoidsetMessageLogging(Printerprinter){
- mLogging=printer;
- }
- /**
- *Returnthe{@linkMessageQueue}objectassociatedwiththecurrent
- *thread.ThismustbecalledfromathreadrunningaLooper,ora
- *NullPointerExceptionwillbethrown.
- */
- publicstaticfinalMessageQueuemyQueue(){
- returnmyLooper().mQueue;
- }
- //创建一个新的looper对象,
- //内部分配一个消息队列,设置mRun为true
- privateLooper(){
- mQueue=newMessageQueue();
- mRun=true;
- mThread=Thread.currentThread();
- }
- publicvoidquit(){
- Messagemsg=Message.obtain();
- //NOTE:Byenqueueingdirectlyintothemessagequeue,the
- //messageisleftwithanulltarget.Thisishowweknowitis
- //aquitmessage.
- mQueue.enqueueMessage(msg,0);
- }
- /**
- *ReturntheThreadassociatedwiththisLooper.
- */
- publicThreadgetThread(){
- returnmThread;
- }
- //后面就简单了,打印,异常定义等。
- publicvoiddump(Printerpw,Stringprefix){
- pw.println(prefix+this);
- pw.println(prefix+"mRun="+mRun);
- pw.println(prefix+"mThread="+mThread);
- pw.println(prefix+"mQueue="+((mQueue!=null)?mQueue:"(null"));
- if(mQueue!=null){
- synchronized(mQueue){
- Messagemsg=mQueue.mMessages;
- intn=0;
- while(msg!=null){
- pw.println(prefix+"Message"+n+":"+msg);
- n++;
- msg=msg.next;
- }
- pw.println(prefix+"(Totalmessages:"+n+")");
- }
- }
- }
- publicStringtoString(){
- return"Looper{"
- +Integer.toHexString(System.identityHashCode(this))
- +"}";
- }
- staticclassHandlerExceptionextendsException{
- HandlerException(Messagemessage,Throwablecause){
- super(createMessage(cause),cause);
- }
- staticStringcreateMessage(Throwablecause){
- StringcauseMsg=cause.getMessage();
- if(causeMsg==null){
- causeMsg=cause.toString();
- }
- returncauseMsg;
- }
- }
- }
那怎么往这个消息队列中发送消息呢??调用looper的static函数myQueue可以获得消息队列,这样你就可用自己往里边插入消息了。不过这种方法比较麻烦,这个时候handler类就发挥作用了。先来看看handler的代码,就明白了。
[cpp]view plaincopy
- classHandler{
- ..........
- //handler默认构造函数
- publicHandler(){
- //这个if是干嘛用的暂时还不明白,涉及到java的深层次的内容了应该
- if(FIND_POTENTIAL_LEAKS){
- finalClass<?extendsHandler>klass=getClass();
- if((klass.isAnonymousClass()||klass.isMemberClass()||klass.isLocalClass())&&
- (klass.getModifiers()&Modifier.STATIC)==0){
- Log.w(TAG,"ThefollowingHandlerclassshouldbestaticorleaksmightoccur:"+
- klass.getCanonicalName());
- }
- }
- //获取本线程的looper对象
- //如果本线程还没有设置looper,这回抛异常
- mLooper=Looper.myLooper();
- if(mLooper==null){
- thrownewRuntimeException(
- "Can'tcreatehandlerinsidethreadthathasnotcalledLooper.prepare()");
- }
- //无耻啊,直接把looper的queue和自己的queue搞成一个了
- //这样的话,我通过handler的封装机制加消息的话,就相当于直接加到了looper的消息队列中去了
- mQueue=mLooper.mQueue;
- mCallback=null;
- }
- //还有好几种构造函数,一个是带callback的,一个是带looper的
- //由外部设置looper
- publicHandler(Looperlooper){
- mLooper=looper;
- mQueue=looper.mQueue;
- mCallback=null;
- }
- //带callback的,一个handler可以设置一个callback。如果有callback的话,
- //凡是发到通过这个handler发送的消息,都有callback处理,相当于一个总的集中处理
- //待会看dispatchMessage的时候再分析
- publicHandler(Looperlooper,Callbackcallback){
- mLooper=looper;
- mQueue=looper.mQueue;
- mCallback=callback;
- }
- //
- //通过handler发送消息
- //调用了内部的一个sendMessageDelayed
- publicfinalbooleansendMessage(Messagemsg)
- {
- returnsendMessageDelayed(msg,0);
- }
- //FT,又封装了一层,这回是调用sendMessageAtTime了
- //因为延时时间是基于当前调用时间的,所以需要获得绝对时间传递给sendMessageAtTime
- publicfinalbooleansendMessageDelayed(Messagemsg,longdelayMillis)
- {
- if(delayMillis<0){
- delayMillis=0;
- }
- returnsendMessageAtTime(msg,SystemClock.uptimeMillis()+delayMillis);
- }
- publicbooleansendMessageAtTime(Messagemsg,longuptimeMillis)
- {
- booleansent=false;
- MessageQueuequeue=mQueue;
- if(queue!=null){
- //把消息的target设置为自己,然后加入到消息队列中
- //对于队列这种数据结构来说,操作比较简单了
- msg.target=this;
- sent=queue.enqueueMessage(msg,uptimeMillis);
- }
- else{
- RuntimeExceptione=newRuntimeException(
- this+"sendMessageAtTime()calledwithnomQueue");
- Log.w("Looper",e.getMessage(),e);
- }
- returnsent;
- }
- //还记得looper中的那个消息循环处理吗
- //从消息队列中得到一个消息后,会调用它的target的dispatchMesage函数
- //message的target已经设置为handler了,所以
- //最后会转到handler的msg处理上来
- //这里有个处理流程的问题
- publicvoiddispatchMessage(Messagemsg){
- //如果msg本身设置了callback,则直接交给这个callback处理了
- if(msg.callback!=null){
- handleCallback(msg);
- }else{
- //如果该handler的callback有的话,则交给这个callback处理了---相当于集中处理
- if(mCallback!=null){
- if(mCallback.handleMessage(msg)){
- return;
- }
- }
- //否则交给派生处理,基类默认处理是什么都不干
- handleMessage(msg);
- }
- }
- ..........
- }
讲了这么多,该怎么创建和使用一个带消息循环的线程呢?
[cpp]view plaincopy
- //假设在onCreate中创建一个线程
- //不花时间考虑代码的完整和严谨性了,以讲述原理为主。
- ....
- ...onCreate(...){
- //难点是如何把android中的looper和java的thread弄到一起去。
- //而且还要把随时取得这个looper用来创建handler
- //最简单的办法就是从Thread派生一个
- classThreadWithMessageHandleextendsThread{
- //重载run函数
- LoopermyLooper=null;
- run(){
- Looper.prepare();//将Looper设置到这个线程中
- myLooper=Looper.myLooper();
- Looper.loop();开启消息循环
- }
- ThreadWithMessageHandlethreadWithMgs=newThreadWithMessageHandle();
- threadWithMsg.start();
- Looperlooper=threadWithMsg.myLooper;//
- //这里有个问题.threadWithMgs中的myLooper可能此时为空
- //需要同步处理一下
- //或者像API文档中的那样,把handler定义到ThreadWithMessageHandle到去。
- //外线程获得这个handler的时候仍然要注意同步的问题,因为handler的创建是在run中的
- HandlerthreadHandler=newHandler(looper);
- threadHandler.sendMessage(...)
- }
- }
- ...
结束。
更多相关文章
- 《Android开发艺术探索》第十章重点笔记
- Android中子线程真的不能更新UI吗?
- Android中Handler的简析
- 报Only the original thread that created a view hierarchy can
- 巧用AsyncTask的onProgressUpdate回调
- android 线程间的通信
- android的消息处理机制(图+源码分析)——Looper,Handler,Message
- Android的WiFi子系统架构
- Android探索之路(一)——消息处理机制