zoukankan      html  css  js  c++  java
  • Looper.loop() android线程中的消息循环

    Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环起作用,从消息队列里取消息,处理消息。
    注:写在Looper.loop()之后的代码不会被立即执行,当调用后mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。
    以下是Android API中的一个典型的Looper thread实现:
    //Handler不带参数的默认构造函数:new Handler(),实际上是通过Looper.myLooper()来获取当前线程中的消息循环, //而默认情况下,线程是没有消息循环的,所以要调用 Looper.prepare()来给线程创建消息循环,然后再通过,Looper.loop()来使消息循环起作用。
    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();

                }

    另,Activity的MainUI线程默认是有消息队列的。所以在Activity中新建Handler时,不需要先调用Looper.prepare()。

    什么时候使用Looper.prepare()

    当你的线程想拥有自己的MessageQueue的时候先Looper.prepare(),然后Looper.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());     
    6.    }     
    public static final void prepare() {   
           if (sThreadLocal.get() != null) {   
               throw new RuntimeException("Only one Looper may be created per thread");   
           }   
           sThreadLocal.set(new Looper());   
       }   

     

     
    这段代码就是通过ThreadLocal来产生一个Looper对象做为线程局部变量,然后调用Looper.loop()则是取出Looper对象中的MessageQueue进行消息循环了,这样形成了这个线程的消息队列。 一般情况下只会有主线程会调用prepare方法(ActivityThread的main函数)。
     

    使线程拥有自己的消息列队,主线程拥有自己的消息列队,一般线程创建时没有自己的消息列队,消息处理时就在主线程中完成,如果线程中使用Looper.prepare()和Looper.loop()创建了消息队列就可以让消息处理在该线程中完成

  • 相关阅读:
    浅谈计算机速度变慢
    日志中的秘密:Windows登录类型知多少?ZT
    在应用程序代码中使用 FOR XML 结果 [From MS]
    Two sql tips
    Web Service Error: “The request failed with HTTP status 401: Unauthorized.”ZT
    [转载]大话MVP
    WCF服务编程 学习笔记(1)
    [转]ExtJS的使用方法汇总—配置和表格控件使用
    [转载]谈谈关于MVP模式中VP交互问题
    [转载]SCSF 系列:Smart Client Software Factory 中 MVP 模式最佳实践
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/3440333.html
Copyright © 2011-2022 走看看