<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    常用鏈接

    統計

    最新評論

    Android Looper(轉)

    (1) Looper類別用來為一個線程開啟一個消息循環。默認情況下Android中新誕生的線程是沒有開啟消息循環的。(主線程除外,主線程系統會自動為其創建Looper對象,開啟消息循環)

    Looper對象通過MessageQueue來存放消息和事件。一個線程只能有一個Looper,對應一個MessageQueue。

    (2) 通常是通過Handler對象來與Looper交互的。Handler可看做是Looper的一個接口,用來向指定的Looper發送消息及定義處理方法。

    默認情況下Handler會與其被定義時所在線程的Looper綁定,比如,在主線程中定義,其是與主線程的Looper綁定。

    mainHandler = new Handler() 等價于new Handler(Looper.myLooper()).

    Looper.myLooper():Return the Looper object associated with the current thread 獲取當前進程的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發送消息即可。

    (6) 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 ofprepare() and loop() to create an initial Handler to communicate with the Looper.

    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();
          }
    }

    posted on 2010-12-20 15:13 九寶 閱讀(395) 評論(0)  編輯  收藏 所屬分類: android

    主站蜘蛛池模板: 四虎成人免费网址在线| 亚洲天堂免费在线| 亚洲日本在线播放| 高清国语自产拍免费视频国产 | 一级毛片免费观看| 久久综合亚洲色一区二区三区| 亚洲欧洲免费无码| 亚洲永久中文字幕在线| 一二三四在线播放免费观看中文版视频 | 国产一区二区三区免费观在线| 国产精品四虎在线观看免费| 韩国免费A级毛片久久| 精品久久久久久亚洲精品| 91麻豆国产自产在线观看亚洲 | 鲁大师在线影院免费观看| 亚洲资源最新版在线观看| 亚洲区不卡顿区在线观看| 啦啦啦完整版免费视频在线观看| 久久水蜜桃亚洲av无码精品麻豆| 久久高潮一级毛片免费| 国产成人亚洲综合网站不卡| 伊人久久大香线蕉亚洲| 午夜视频免费观看| 久久ww精品w免费人成| 一级一看免费完整版毛片| 亚洲三级在线观看| 亚洲VA成无码人在线观看天堂| 国产精品99久久免费观看| 亚洲精品无码久久久久牙蜜区| 国产免费怕怕免费视频观看| 亚洲香蕉免费有线视频| 中文在线免费不卡视频| 亚洲αⅴ无码乱码在线观看性色| 国产免费AV片无码永久免费| 1000部免费啪啪十八未年禁止观看| 亚洲中文字幕人成乱码| 亚洲成av人影院| 中文字幕亚洲无线码a| 国产一级高清免费观看| 最近2019中文字幕免费看最新| 黄色一级视频免费|