android Handler介紹,androidhandler介紹

來源:互聯網
上載者:User

android Handler介紹,androidhandler介紹

Handler使用介紹:

Handler根據接收的訊息,處理UI更新。Thread線程發出訊息,通知Handler更新UI。

Handler mHandler = new Handler() { 
  public void handleMessage(Message msg) {  
    switch (msg.what) {  
    case 0x1:  
      view.invalidate(); 
      break;  
    }  
    super.handleMessage(msg);  
  }  
};

class UpdateViewThread implements Runnable {  
  public void run() { 
    while (!Thread.currentThread().isInterrupted()) {    
      Message message = new Message();  
      message.what = 0x1;   
      mHandler.sendMessage(message);  
      try {  
        Thread.sleep(200);   
      } catch (InterruptedException e) {  
        Thread.currentThread().interrupt();  
      }  
    }  
  }  

(1)對於線程中的重新整理一個View為基類的介面,可以使用postInvalidate()方法線上程中來處理,其中還提供了一些重寫方法比如postInvalidate(int left,int top,int right,int bottom) 來重新整理一個矩形地區,以及延時執行,比如postInvalidateDelayed(long delayMilliseconds)或postInvalidateDelayed(long delayMilliseconds,int left,int top,int right,int bottom) 方法,其中第一個參數為毫秒

(2)可以在一個線程的run方法中調用Handler對象的postMessage或sendMessage方法來實現,Android程式內部維護著一個訊息佇列,會進行輪詢處理。

(3)在Android中每一個Thread都跟著一個Looper,Looper可以協助Thread維護一個訊息佇列,但是Looper和Handler沒有什麼關係,從源碼中可以看到Android提供了一個Thread繼承類HanderThread可以協助我們處理,在HandlerThread對象中可以通過getLooper方法擷取一個Looper對象控制控制代碼,我們可以將這個Looper對象映射到一個Handler中來實現一個線程同步機制,Looper對象的執行需要進行初始化,可以調用Looper.prepare,使用Looper.release方法釋放資源。

(4)對於Android中Handler可以傳遞一些內容,通過Bundle對象可以封裝String、Integer以及Blob二進位對象,我們通過線上程中使用Handler對象的sendEmptyMessage或sendMessage方法來傳遞一個Bundle對象到Handler處理器。對於Handler類提供了重寫方法handleMessage(Message msg) 來判斷,通過msg.what來區分每條資訊。將Bundle解包來實現Handler類更新UI線程中的內容實現控制項的重新整理操作。相關的Handler對象有關訊息發送sendXXX相關方法如下,同時還有postXXX相關方法,一個為發送後直接返回,一個為處理後才返回。

(5)在Android中提供了一種有別於線程的處理方式,就是Task以及AsyncTask,從源碼中可以看到是針對Concurrent的封裝,開發人員可以方便的處理這些非同步任務。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.