zoukankan      html  css  js  c++  java
  • Handler 、 Looper 、Message

    分析:

    Looper:prepare和loop

    1 public static final void prepare() {
    2         if (sThreadLocal.get() != null) {
    3             throw new RuntimeException("Only one Looper may be created per thread");
    4         }
    5         sThreadLocal.set(new Looper(true));
    6 }

    由上述方法可知,第5行新建一个Looper实例然后添加到sThreadLocal中,上面首先判断sThreadLocal是否为空,若不为空则抛出异常,说明Looper.prepare()方法不能被调用两次,同时也保证了一个线程中只有一个Looper实例

    Looper的构造方法:

    1 private Looper(boolean quitAllowed) {
    2         mQueue = new MessageQueue(quitAllowed);
    3         mRun = true;
    4         mThread = Thread.currentThread();
    5 }

    由第2行可知创建了一个MessageQueue消息队列

    loop方法:

     1 public static void loop() {
     2         final Looper me = myLooper();
     3         if (me == null) {
     4             throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
     5         }
     6         final MessageQueue queue = me.mQueue;
     7 
     8         // Make sure the identity of this thread is that of the local process,
     9         // and keep track of what that identity token actually is.
    10         Binder.clearCallingIdentity();
    11         final long ident = Binder.clearCallingIdentity();
    12 
    13         for (;;) {
    14             Message msg = queue.next(); // might block
    15             if (msg == null) {
    16                 // No message indicates that the message queue is quitting.
    17                 return;
    18             }
    19 
    20             // This must be in a local variable, in case a UI event sets the logger
    21             Printer logging = me.mLogging;
    22             if (logging != null) {
    23                 logging.println(">>>>> Dispatching to " + msg.target + " " +
    24                         msg.callback + ": " + msg.what);
    25             }
    26 
    27             msg.target.dispatchMessage(msg);
    28 
    29             if (logging != null) {
    30                 logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
    31             }
    32 
    33             // Make sure that during the course of dispatching the
    34             // identity of the thread wasn't corrupted.
    35             final long newIdent = Binder.clearCallingIdentity();
    36             if (ident != newIdent) {
    37                 Log.wtf(TAG, "Thread identity changed from 0x"
    38                         + Long.toHexString(ident) + " to 0x"
    39                         + Long.toHexString(newIdent) + " while dispatching to "
    40                         + msg.target.getClass().getName() + " "
    41                         + msg.callback + " what=" + msg.what);
    42             }
    43 
    44             msg.recycle();
    45         }
    46 }

    第2行调用myLooper():其源码为

    public static Looper myLooper() {
    return sThreadLocal.get();
    }

    Return the Looper object associated with the current thread.返回与当前线程相关联的looper对象赋给me,如果me为null则抛异常,表示looper方法必须在prepare方法之后运行

    注:但是有一个疑问:首先贴上我们平常创建handler的代码:

     1 public class MainActivity extends Activity {
     2     
     3     private Handler handler1;
     4     
     5     private Handler handler2;
     6 
     7     @Override
     8     protected void onCreate(Bundle savedInstanceState) {
     9         super.onCreate(savedInstanceState);
    10         setContentView(R.layout.activity_main);
    11         handler1 = new Handler();
    12         new Thread(new Runnable() {
    13             @Override
    14             public void run() {
    15                 handler2 = new Handler();
    16             }
    17         }).start();
    18     }
    19 
    20 }

    运行会发现在子线程中创建的Handler是会导致程序崩溃的,提示的错误信息为 Can't create handler inside thread that has not called Looper.prepare() 。说是不能在没有调用Looper.prepare() 的线程中创建Handler,所以在里面添加Looper.prepare(); 该行代码后就正常了,但是主线程中也没有添加改行代码,为何就不崩溃呢?原因在于程序启动的时候,系统已经帮我们自动调用了Looper.prepare()方法,上ActivityThread中的main()方法的源码:

     1 public static void main(String[] args) {
     2     SamplingProfilerIntegration.start();
     3     CloseGuard.setEnabled(false);
     4     Environment.initForCurrentUser();
     5     EventLogger.setReporter(new EventLoggingReporter());
     6     Process.setArgV0("<pre-initialized>");
     7     Looper.prepareMainLooper();
     8     ActivityThread thread = new ActivityThread();
     9     thread.attach(false);
    10     if (sMainThreadHandler == null) {
    11         sMainThreadHandler = thread.getHandler();
    12     }
    13     AsyncTask.init();
    14     if (false) {
    15         Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread"));
    16     }
    17     Looper.loop();
    18     throw new RuntimeException("Main thread loop unexpectedly exited");
    19 }

    由第7行可知调用了 Looper.prepareMainLooper();方法,而该方法又会去调用Looper.prepare()方法:

    1 public static final void prepareMainLooper() {
    2     prepare();
    3     setMainLooper(myLooper());
    4     if (Process.supportsProcesses()) {
    5         myLooper().mQueue.mQuitAllowed = false;
    6     }
    7 }

    第2行可知,至此搞清楚了我们应用程序的主线程中会始终存在一个Looper对象,从而不需要再手动去调用Looper.prepare()方法

    第6行:拿到该looper实例中的mQueue(消息队列)
    13到45行:就进入了我们所说的无限循环。
    14行:取出一条消息,如果没有消息则阻塞。
    27行:使用调用 msg.target.dispatchMessage(msg);把消息交给msg的target的dispatchMessage方法去处理。Msg的target是什么呢?其实就是handler对象,下面会进行分析。
    44行:释放消息占据的资源。

    由上述分析可知;Looper主要作用:
    1、 与当前线程绑定,保证一个线程只会有一个Looper实例,同时一个Looper实例也只有一个MessageQueue。
    2、 loop()方法,不断从MessageQueue中去取消息,交给消息的target属性的dispatchMessage去处理。

    异步消息处理线程已经有了消息队列(MessageQueue),同时也就有了从消息队列中取对象的东东了(Looper),接下来就是发送消息的Handler

    Handler:

    我们在使用Handler是都是直接在UI线程中直接new一个实例,具体他是如何跟子线程中的MessageQueue联系上并发送消息的的呢?直接上源码

     1 public Handler() {
     2         this(null, false);
     3 }
     4 public Handler(Callback callback, boolean async) {
     5         if (FIND_POTENTIAL_LEAKS) {
     6             final Class<? extends Handler> klass = getClass();
     7             if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
     8                     (klass.getModifiers() & Modifier.STATIC) == 0) {
     9                 Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
    10                     klass.getCanonicalName());
    11             }
    12         }
    13 
    14         mLooper = Looper.myLooper();
    15         if (mLooper == null) {
    16             throw new RuntimeException(
    17                 "Can't create handler inside thread that has not called Looper.prepare()");
    18         }
    19         mQueue = mLooper.mQueue;
    20         mCallback = callback;
    21         mAsynchronous = async;
    22     }

    14行:通过Looper.myLooper()获取了当前线程保存的Looper实例,然后在19行又获取了这个Looper实例中保存的MessageQueue(消息队列),这样就保证了handler的实例与我们Looper实例中MessageQueue关联上了。

    平常我们是如何在子线程中发送消息的呢?

     1 new Thread(new Runnable() {
     2     @Override
     3     public void run() {
     4         Message message = new Message();
     5         message.arg1 = 1;
     6         Bundle bundle = new Bundle();
     7         bundle.putString("data", "data");
     8         message.setData(bundle);
     9         handler.sendMessage(message);
    10     }
    11 }).start();

    由第9行可知我们调用了sendMessage方法,于是我们来看看该方法的源码:

    1    public final boolean sendMessage(Message msg)
    2     {
    3         return sendMessageDelayed(msg, 0);
    4     }

    转而会去调用sendMessageDelayed(msg, 0);方法:

    1    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
    2         Message msg = Message.obtain();
    3         msg.what = what;
    4         return sendMessageDelayed(msg, delayMillis);
    5     }
    1  public final boolean sendMessageDelayed(Message msg, long delayMillis)
    2     {
    3         if (delayMillis < 0) {
    4             delayMillis = 0;
    5         }
    6         return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    7     }
     1  public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
     2         MessageQueue queue = mQueue;
     3         if (queue == null) {
     4             RuntimeException e = new RuntimeException(
     5                     this + " sendMessageAtTime() called with no mQueue");
     6             Log.w("Looper", e.getMessage(), e);
     7             return false;
     8         }
     9         return enqueueMessage(queue, msg, uptimeMillis);
    10     }

    附新的版本:

     1 public boolean sendMessageAtTime(Message msg, long uptimeMillis)
     2 {
     3     boolean sent = false;
     4     MessageQueue queue = mQueue;
     5     if (queue != null) {
     6         msg.target = this;
     7         sent = queue.enqueueMessage(msg, uptimeMillis);
     8     }
     9     else {
    10         RuntimeException e = new RuntimeException(
    11             this + " sendMessageAtTime() called with no mQueue");
    12         Log.w("Looper", e.getMessage(), e);
    13     }
    14     return sent;
    15 }

    由上可知Handler中提供了很多个发送消息的方法,其中除了sendMessageAtFrontOfQueue()方法之外,其它的发送消息方法最终都会辗转调用到sendMessageAtTime()方法中,查看该方法源码可知:该方法在内部直接获取了MessageQueue的实例,然后返回调用了enqueueMessage方法,

    由第2行代码可知mQueue实例是在Looper的构造方法中创建的消息队列实例对象, 它调用了enqueueMessage方法,可知它是一个消息队列,用于将所有收到的消息以队列的形式进行排列,并提供入队和出队的方法。这个类是在Looper的构造函数中创建的,因此一个Looper也就对应了一个MessageQueue

    接着去查看该方法源码:

    1  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    2         msg.target = this;
    3         if (mAsynchronous) {
    4             msg.setAsynchronous(true);
    5         }
    6         return queue.enqueueMessage(msg, uptimeMillis);
    7     }

    enqueueMessage中首先为meg.target赋值为this,【如果大家还记得Looper的loop方法会取出每个msg然后交给msg,target.dispatchMessage(msg)去处理消息】,也就是把当前的handler作为msg的target属性。最终会调用queue的enqueueMessage的方法,也就是说handler发出的消息,最终会保存到消息队列中去

    现在已经很清楚了Looper会调用prepare()和loop()方法,在当前执行的线程中保存一个Looper实例,这个实例会保存一个MessageQueue对象,然后当前线程进入一个无限循环中去,不断从MessageQueue中读取Handler发来的消息。然后再回调创建这个消息的handler中的dispathMessage方法,下面我们赶快去看一看这个方法:

     1 public void dispatchMessage(Message msg) {
     2         if (msg.callback != null) {
     3             handleCallback(msg);
     4         } else {
     5             if (mCallback != null) {
     6                 if (mCallback.handleMessage(msg)) {
     7                     return;
     8                 }
     9             }
    10             handleMessage(msg);
    11         }
    12     }

    可以看到,第10行,调用了handleMessage方法,下面我们去看这个方法:

      /**
         * Subclasses must implement this to receive messages.
         */
        public void handleMessage(Message msg) {
        }
        

    可以看到这是一个空方法,为什么呢,因为消息的最终回调是由我们控制的,我们在创建handler的时候都是复写handleMessage方法,然后根据msg.what进行消息处理。

    例如:

     1 private Handler mHandler = new Handler()
     2     {
     3         public void handleMessage(android.os.Message msg)
     4         {
     5             switch (msg.what)
     6             {
     7             case value:
     8                 
     9                 break;
    10 
    11             default:
    12                 break;
    13             }
    14         };
    15     };

    至此,整个处理机制解释完毕,下面总结一下:

    1、首先Looper.prepare()在本线程中保存一个Looper实例,然后该实例中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。

    2、Looper.loop()会让当前线程进入一个无限循环,不端从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。

    3、Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue相关联。

    4、Handler的sendMessage方法,会给msg的target赋值为handler自身,然后加入MessageQueue中。

    5、在构造Handler实例时,我们会重写handleMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。

    整个异步处理流程如下图所示:

    另外除了发送消息之外,我们还有以下几种方法可以在子线程中进行UI操作:

    1. Handler的post()方法

    2. View的post()方法

    3. Activity的runOnUiThread()方法

    我们先来看下Handler中的post()方法,代码如下所示:

    1 public final boolean post(Runnable r)
    2 {
    3    return  sendMessageDelayed(getPostMessage(r), 0);
    4 }

    原来这里还是调用了sendMessageDelayed()方法去发送一条消息啊,并且还使用了getPostMessage()方法将Runnable对象转换成了一条消息,我们来看下这个方法的源码:

    1 private final Message getPostMessage(Runnable r) {
    2     Message m = Message.obtain();
    3     m.callback = r;
    4     return m;
    5 }

    在这个方法中将消息的callback字段的值指定为传入的Runnable对象。咦?这个callback字段看起来有些眼熟啊,喔!在Handler的dispatchMessage()方法中原来有做一个检查,如果Message的callback等于null才会去调用handleMessage()方法,否则就调用handleCallback()方法。那我们快来看下handleCallback()方法中的代码吧:

    1 private final void handleCallback(Message message) {
    2     message.callback.run();
    3 }

    也太简单了!竟然就是直接调用了一开始传入的Runnable对象的run()方法。因此在子线程中通过Handler的post()方法进行UI操作就可以这么写:

     1 public class MainActivity extends Activity {
     2 
     3     private Handler handler;
     4 
     5     @Override
     6     protected void onCreate(Bundle savedInstanceState) {
     7         super.onCreate(savedInstanceState);
     8         setContentView(R.layout.activity_main);
     9         handler = new Handler();
    10         new Thread(new Runnable() {
    11             @Override
    12             public void run() {
    13                 handler.post(new Runnable() {
    14                     @Override
    15                     public void run() {
    16                         // 在这里进行UI操作
    17                     }
    18                 });
    19             }
    20         }).start();
    21     }
    22 }

    虽然写法上相差很多,但是原理是完全一样的,我们在Runnable对象的run()方法里更新UI,效果完全等同于在handleMessage()方法中更新UI。

    然后再来看一下View中的post()方法,代码如下所示:

     1 public boolean post(Runnable action) {
     2     Handler handler;
     3     if (mAttachInfo != null) {
     4         handler = mAttachInfo.mHandler;
     5     } else {
     6         ViewRoot.getRunQueue().post(action);
     7         return true;
     8     }
     9     return handler.post(action);
    10 }

    原来就是调用了Handler中的post()方法,我相信已经没有什么必要再做解释了。

    最后再来看一下Activity中的runOnUiThread()方法,代码如下所示:

    1 public final void runOnUiThread(Runnable action) {
    2     if (Thread.currentThread() != mUiThread) {
    3         mHandler.post(action);
    4     } else {
    5         action.run();
    6     }
    7 }

    如果当前的线程不等于UI线程(主线程),就去调用Handler的post()方法,否则就直接调用Runnable对象的run()方法。还有什么会比这更清晰明了的吗?

    附:关于obtainMessage():

    对于handler.obtainMessage()的分析:

    1  /**
    2      * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
    3      * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
    4      *  If you don't want that facility, just call Message.obtain() instead.
    5      */
    6     public final Message obtainMessage()
    7     {
    8         return Message.obtain(this);
    9     }
     1   /**
     2      * Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
     3      * @param h  Handler to assign to the returned Message object's <em>target</em> member.
     4      * @return A Message object from the global pool.
     5      */
     6     public static Message obtain(Handler h) {
     7         Message m = obtain();
     8         m.target = h;
     9 
    10         return m;
    11     }
     1 /**
     2      * Return a new Message instance from the global pool. Allows us to
     3      * avoid allocating new objects in many cases.
     4      */
     5     public static Message obtain() {
     6         synchronized (sPoolSync) {
     7             if (sPool != null) {
     8                 Message m = sPool;
     9                 sPool = m.next;
    10                 m.next = null;
    11                 sPoolSize--;
    12                 return m;
    13             }
    14         }
    15         return new Message();
    16     }

    从上面源码可知:obtainMessage()会在内部调用obtain(Handler h) ,接着会在内部调用Message m = obtain();而从obtain()源码中可以看出它会首先从全局消息池中取出message实例,如果池中没有时才会创建新的Message实例,所以在性能上会比直接new Message对象更好一些

  • 相关阅读:
    【Codeforces Round #645 (Div. 2) A】 Park Lighting
    【Codeforces Round #636 (Div. 3) D】Constant Palindrome Sum
    【Codeforces Round #628 (Div. 2) D】Ehab the Xorcist
    【Codeforces Round #642 (Div. 3)】Constructing the Array
    【LeetCode 85】最大矩形(第二遍)
    scrum例会报告+燃尽图02
    scrum例会报告+燃尽图01
    版本控制报告
    Scrum立会报告+燃尽图 07
    Scrum立会报告+燃尽图 05
  • 原文地址:https://www.cnblogs.com/CoolRandy/p/4541574.html
Copyright © 2011-2022 走看看