服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android消息处理机制Looper和Handler详解

Android消息处理机制Looper和Handler详解

2021-03-09 15:06Android开发网 Android

Android应用程序是通过消息来驱动的,系统为每一个应用程序维护一个消息队例,应用程序的主线程不断地从这个消息队例中获取消息(Looper),然后对这些消息进行处理(Handler),这样就实现了通过消息来驱动应用程序的执行,本

?
1
2
3
4
5
Message:消息,其中包含了消息ID,消息处理对象以及处理的数据等,由MessageQueue统一列队,终由Handler处理。
Handler:处理者,负责Message的发送及处理。使用Handler时,需要实现handleMessage(Message msg)方法来对特定的Message进行处理,例如更新UI等。
MessageQueue:消息队列,用来存放Handler发送过来的消息,并按照FIFO规则执行。当然,存放Message并非实际意义的保存,而是将Message以链表的方式串联起来的,等待Looper的抽取。
Looper:消息泵,不断地从MessageQueue中抽取Message执行。因此,一个MessageQueue需要一个Looper。
Thread:线程,负责调度整个消息循环,即消息循环的执行场所。

Android系统的消息队列和消息循环都是针对具体线程的,一个线程可以存在(当然也可以不存在)一个消息队列和一个消 息循环(Looper),特定线程的消息只能分发给本线程,不能进行跨线程,跨进程通讯。但是创建的工作线程默认是没有消息循环和消息队列的,如果想让该 线程具有消息队列和消息循环,需要在线程中首先调用Looper.prepare()来创建消息队列,然后调用Looper.loop()进入消息循环。 如下例所示:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
LooperThread Thread {
   Handler mHandler;
 
   run() {
    Looper.prepare();
 
    mHandler = Handler() {
       handleMessage(Message msg) {
        
      }
    };
 
    Looper.loop();
  }
}

 //Looper类分析
 //没找到合适的分析代码的办法,只能这么来了。每个重要行的上面都会加上注释
 //功能方面的代码会在代码前加上一段分析

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
public class Looper {
  //static变量,判断是否打印调试信息。
   private static final boolean DEBUG = false;
   private static final boolean localLOGV = DEBUG ? Config.LOGD : Config.LOGV;
 
   // sThreadLocal.get() will return null unless you've called prepare().
 //线程本地存储功能的封装,TLS,thread local storage,什么意思呢?因为存储要么在栈上,例如函数内定义的内部变量。要么在堆上,例如new或者malloc出来的东西
 //但是现在的系统比如Linux和windows都提供了线程本地存储空间,也就是这个存储空间是和线程相关的,一个线程内有一个内部存储空间,这样的话我把线程相关的东西就存储到
 //这个线程的TLS中,就不用放在堆上而进行同步操作了。
   private static final ThreadLocal sThreadLocal = new ThreadLocal();
 //消息队列,MessageQueue,看名字就知道是个queue..
   final MessageQueue mQueue;
   volatile boolean mRun;
 //和本looper相关的那个线程,初始化为null
   Thread mThread;
   private Printer mLogging = null;
 //static变量,代表一个UI Process(也可能是service吧,这里默认就是UI)的主线程
   private static Looper mMainLooper = null;
   
   /** Initialize the current thread as a looper.
    * This gives you a chance to create handlers that then reference
    * this looper, before actually starting the loop. Be sure to call
    * {@link #loop()} after calling this method, and end it by calling
    * {@link #quit()}.
    */
 //往TLS中设上这个Looper对象的,如果这个线程已经设过了looper的话就会报错
 //这说明,一个线程只能设一个looper
   public static final void prepare() {
     if (sThreadLocal.get() != null) {
       throw new RuntimeException("Only one Looper may be created per thread");
     }
     sThreadLocal.set(new Looper());
   }
   
   /** Initialize the current thread as a looper, marking it as an application's main
   * looper. The main looper for your application is created by the Android environment,
   * so you should never need to call this function yourself.
   * {@link #prepare()}
   */
 //由framework设置的UI程序的主消息循环,注意,这个主消息循环是不会主动退出的
 // 
   public static final void prepareMainLooper() {
     prepare();
     setMainLooper(myLooper());
 //判断主消息循环是否能退出....
 //通过quit函数向looper发出退出申请
     if (Process.supportsProcesses()) {
       myLooper().mQueue.mQuitAllowed = false;
     }
   }
 
   private synchronized static void setMainLooper(Looper looper) {
     mMainLooper = looper;
   }
   
   /** Returns the application's main looper, which lives in the main thread of the application.
   */
   public synchronized static final Looper getMainLooper() {
     return mMainLooper;
   }
 
   /**
   * Run the message queue in this thread. Be sure to call
   * {@link #quit()} to end the loop.
   */
 //消息循环,整个程序就在这里while了。
 //这个是static函数喔!
   public static final void loop() {
     Looper me = myLooper();//从该线程中取出对应的looper对象
     MessageQueue queue = me.mQueue;//取消息队列对象...
     while (true) {
       Message msg = queue.next(); // might block取消息队列中的一个待处理消息..
       //if (!me.mRun) {//是否需要退出?mRun是个volatile变量,跨线程同步的,应该是有地方设置它。
       //  break;
       //}
       if (msg != null) {
         if (msg.target == null) {
           // No target is a magic identifier for the quit message.
           return;
         }
         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.println(
             "<<<<< Finished to  " + msg.target + " "
             + msg.callback);
         msg.recycle();
       }
     }
   }
 
   /**
   * Return the Looper object associated with the current thread. Returns
   * null if the calling thread is not associated with a Looper.
  */
//返回和线程相关的looper
 public static final Looper myLooper() {
   return (Looper)sThreadLocal.get();
 }
 
 /**
  * Control logging of messages as they are processed by this Looper. If
  * enabled, a log message will be written to <var>printer</var>
  * at the beginning and ending of each message dispatch, identifying the
  * target Handler and message contents.
  *
  * @param printer A Printer object that will receive log messages, or
  * null to disable message logging.
  */
//设置调试输出对象,looper循环的时候会打印相关信息,用来调试用最好了。
 public void setMessageLogging(Printer printer) {
   mLogging = printer;
 }
 
 /**
  * Return the {@link MessageQueue} object associated with the current
  * thread. This must be called from a thread running a Looper, or a
  * NullPointerException will be thrown.
  */
 public static final MessageQueue myQueue() {
   return myLooper().mQueue;
 }
//创建一个新的looper对象,
//内部分配一个消息队列,设置mRun为true
 private Looper() {
   mQueue = new MessageQueue();
   mRun = true;
   mThread = Thread.currentThread();
 }
 
 public void quit() {
   Message msg = Message.obtain();
   // NOTE: By enqueueing directly into the message queue, the
   // message is left with a null target. This is how we know it is
   // a quit message.
   mQueue.enqueueMessage(msg, 0);
 }
 
 /**
  * Return the Thread associated with this Looper.
  */
 public Thread getThread() {
   return mThread;
 }
 //后面就简单了,打印,异常定义等。
 public void dump(Printer pw, String prefix) {
   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) {
       Message msg = mQueue.mMessages;
       int n = 0;
       while (msg != null) {
         pw.println(prefix + " Message " + n + ": " + msg);
         n++;
         msg = msg.next;
       }
       pw.println(prefix + "(Total messages: " + n + ")");
     }
   }
 }
 
 public String toString() {
   return "Looper{"
     + Integer.toHexString(System.identityHashCode(this))
     + "}";
 }
 
 static class HandlerException extends Exception {
 
   HandlerException(Message message, Throwable cause) {
     super(createMessage(cause), cause);
   }
 
   static String createMessage(Throwable cause) {
     String causeMsg = cause.getMessage();
     if (causeMsg == null) {
       causeMsg = cause.toString();
     }
     return causeMsg;
   }
 }
}

那怎么往这个消息队列中发送消息呢??调用looper的static函数myQueue可以获得消息队列,这样你就可用自己往里边插入消息了。不过这种方法比较麻烦,这个时候handler类就发挥作用了。先来看看handler的代码,就明白了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Handler{
..........
//handler默认构造函数
public Handler() {
//这个if是干嘛用的暂时还不明白,涉及到java的深层次的内容了应该
    if (FIND_POTENTIAL_LEAKS) {
      final Class<? extends Handler> klass = getClass();
      if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
          (klass.getModifiers() & Modifier.STATIC) == 0) {
        Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
          klass.getCanonicalName());
      }
    }
//获取本线程的looper对象
//如果本线程还没有设置looper,这回抛异常
    mLooper = Looper.myLooper();
    if (mLooper == null) {
      throw new RuntimeException(
        "Can't create handler inside thread that has not called Looper.prepare()");
    }
//无耻啊,直接把looper的queue和自己的queue搞成一个了
//这样的话,我通过handler的封装机制加消息的话,就相当于直接加到了looper的消息队列中去了
    mQueue = mLooper.mQueue;
    mCallback = null;
  }
//还有好几种构造函数,一个是带callback的,一个是带looper的
//由外部设置looper
  public Handler(Looper looper) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = null;
  }
// 带callback的,一个handler可以设置一个callback。如果有callback的话,
//凡是发到通过这个handler发送的消息,都有callback处理,相当于一个总的集中处理
//待会看dispatchMessage的时候再分析
public Handler(Looper looper, Callback callback) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
  }
//
//通过handler发送消息
//调用了内部的一个sendMessageDelayed
public final boolean sendMessage(Message msg)
  {
    return sendMessageDelayed(msg, 0);
  }
//FT,又封装了一层,这回是调用sendMessageAtTime了
//因为延时时间是基于当前调用时间的,所以需要获得绝对时间传递给sendMessageAtTime
public final boolean sendMessageDelayed(Message msg, long delayMillis)
  {
    if (delayMillis < 0) {
      delayMillis = 0;
    }
    return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
  }
 
 
public boolean sendMessageAtTime(Message msg, long uptimeMillis)
  {
    boolean sent = false;
    MessageQueue queue = mQueue;
    if (queue != null) {
//把消息的target设置为自己,然后加入到消息队列中
//对于队列这种数据结构来说,操作比较简单了
      msg.target = this;
      sent = queue.enqueueMessage(msg, uptimeMillis);
    }
    else {
      RuntimeException e = new RuntimeException(
        this + " sendMessageAtTime() called with no mQueue");
      Log.w("Looper", e.getMessage(), e);
    }
    return sent;
  }
//还记得looper中的那个消息循环处理吗
//从消息队列中得到一个消息后,会调用它的target的dispatchMesage函数
//message的target已经设置为handler了,所以
//最后会转到handler的msg处理上来
//这里有个处理流程的问题
public void dispatchMessage(Message msg) {
//如果msg本身设置了callback,则直接交给这个callback处理了
    if (msg.callback != null) {
      handleCallback(msg);
    } else {
//如果该handler的callback有的话,则交给这个callback处理了---相当于集中处理
     if (mCallback != null) {
        if (mCallback.handleMessage(msg)) {
          return;
        }
     }
//否则交给派生处理,基类默认处理是什么都不干
      handleMessage(msg);
    }
  }
..........
}

生成

?
1
2
3
Message msg = mHandler.obtainMessage();
msg.what = what;
msg.sendToTarget();

发送

?
1
2
3
4
5
MessageQueue queue = mQueue;
if (queue != null) {
  msg.target = this;
  sent = queue.enqueueMessage(msg, uptimeMillis);
}

在Handler.java的sendMessageAtTime(Message msg, long uptimeMillis)方法中,我们看到,它找到它所引用的MessageQueue,然后将Message的target设定成自己(目的是为了在处理消息环节,Message能找到正确的Handler),再将这个Message纳入到消息队列中。

抽取

?
1
2
3
4
5
6
7
8
9
10
11
12
13
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {
  Message msg = queue.next(); // might block
  if (msg != null) {
    if (msg.target == null) {
      // No target is a magic identifier for the quit message.
      return;
    }
    msg.target.dispatchMessage(msg);
    msg.recycle();
  }
}

在Looper.java的loop()函数里,我们看到,这里有一个死循环,不断地从MessageQueue中获取下一个(next方法)Message,然后通过Message中携带的target信息,交由正确的Handler处理(dispatchMessage方法)。

处理

?
1
2
3
4
5
6
7
8
9
10
if (msg.callback != null) {
  handleCallback(msg);
} else {
  if (mCallback != null) {
    if (mCallback.handleMessage(msg)) {
      return;
    }
  }
  handleMessage(msg);
}

在Handler.java的dispatchMessage(Message msg)方法里,其中的一个分支就是调用handleMessage方法来处理这条Message,而这也正是我们在职责处描述使用Handler时需要实现handleMessage(Message msg)的原因。

至于dispatchMessage方法中的另外一个分支,我将会在后面的内容中说明。

至此,我们看到,一个Message经由Handler的发送,MessageQueue的入队,Looper的抽取,又再一次地回到Handler的怀抱。而绕的这一圈,也正好帮助我们将同步操作变成了异步操作。

3)剩下的部分,我们将讨论一下Handler所处的线程及更新UI的方式。

在主线程(UI线程)里,如果创建Handler时不传入Looper对象,那么将直接使用主线程(UI线程)的Looper对象(系统已经帮我们创建了);在其它线程里,如果创建Handler时不传入Looper对象,那么,这个Handler将不能接收处理消息。在这种情况下,通用的作法是:

?
1
2
3
4
5
6
7
8
9
10
11
12
class LooperThread extends Thread {
        public Handler mHandler;
        public void run() {
                Looper.prepare();
                mHandler = new Handler() {
                        public void handleMessage(Message msg) {
                               // process incoming messages here
                        }
                };
                Looper.loop();
        }
}

在创建Handler之前,为该线程准备好一个Looper(Looper.prepare),然后让这个Looper跑起来(Looper.loop),抽取Message,这样,Handler才能正常工作。

因此,Handler处理消息总是在创建Handler的线程里运行。而我们的消息处理中,不乏更新UI的操作,不正确的线程直接更新UI将引发异常。因此,需要时刻关心Handler在哪个线程里创建的。

如何更新UI才能不出异常呢?SDK告诉我们,有以下4种方式可以从其它线程访问UI线程:

·      Activity.runOnUiThread(Runnable)
·      View.post(Runnable)
·      View.postDelayed(Runnable, long)
·      Handler
其中,重点说一下的是View.post(Runnable)方法。在post(Runnable action)方法里,View获得当前线程(即UI线程)的Handler,然后将action对象post到Handler里。在Handler里,它将传递过来的action对象包装成一个Message(Message的callback为action),然后将其投入UI线程的消息循环中。在Handler再次处理该Message时,有一条分支(未解释的那条)就是为它所设,直接调用runnable的run方法。而此时,已经路由到UI线程里,因此,我们可以毫无顾虑的来更新UI。

4) 几点小结

·      Handler的处理过程运行在创建Handler的线程里
·      一个Looper对应一个MessageQueue
·      一个线程对应一个Looper
·      一个Looper可以对应多个Handler
·      不确定当前线程时,更新UI时尽量调用post方法

延伸 · 阅读

精彩推荐
  • AndroidAndroid程序设计之AIDL实例详解

    Android程序设计之AIDL实例详解

    这篇文章主要介绍了Android程序设计的AIDL,以一个完整实例的形式较为详细的讲述了AIDL的原理及实现方法,需要的朋友可以参考下...

    Android开发网4622021-03-09
  • Android汇总Android视频录制中常见问题

    汇总Android视频录制中常见问题

    这篇文章主要汇总了Android视频录制中常见问题,帮助大家更好地解决Android视频录制中常见的问题,需要的朋友可以参考下...

    yh_thu5192021-04-28
  • AndroidAndroid实现固定屏幕显示的方法

    Android实现固定屏幕显示的方法

    这篇文章主要介绍了Android实现固定屏幕显示的方法,实例分析了Android屏幕固定显示所涉及的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    鉴客6182021-03-27
  • AndroidAndroid CardView+ViewPager实现ViewPager翻页动画的方法

    Android CardView+ViewPager实现ViewPager翻页动画的方法

    本篇文章主要介绍了Android CardView+ViewPager实现ViewPager翻页动画的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    Abby代黎明9592022-03-02
  • AndroidAndroid中AsyncTask详细介绍

    Android中AsyncTask详细介绍

    这篇文章主要介绍了Android中AsyncTask详细介绍,AsyncTask是一个很常用的API,尤其异步处理数据并将数据应用到视图的操作场合,需要的朋友可以参考下...

    Android开发网7432021-03-11
  • AndroidAndroid实现Service获取当前位置(GPS+基站)的方法

    Android实现Service获取当前位置(GPS+基站)的方法

    这篇文章主要介绍了Android实现Service获取当前位置(GPS+基站)的方法,较为详细的分析了Service基于GPS位置的技巧,具有一定参考借鉴价值,需要的朋友可以参考下...

    Ruthless8332021-03-31
  • AndroidAndroid编程解析XML方法详解(SAX,DOM与PULL)

    Android编程解析XML方法详解(SAX,DOM与PULL)

    这篇文章主要介绍了Android编程解析XML方法,结合实例形式详细分析了Android解析XML文件的常用方法与相关实现技巧,需要的朋友可以参考下...

    liuhe68810042021-05-03
  • AndroidAndroid界面效果UI开发资料汇总(附资料包)

    Android界面效果UI开发资料汇总(附资料包)

    android ui界面设计,友好的界面会提高用户体验度;同时也增强了android ui界面设计的难度,本文提供了一些常用开发资料(有下载哦)感兴趣的朋友可以了解下...

    Android开发网4652021-01-03