android中Invalidate和postInvalidate的區別

轉自 https://www.cnblogs.com/rayray/p/3437048.html

Android中實現view的更新有兩組方法,一組是invalidate,另一組是postInvalidate,其中前者是在UI線程自身中使用,而後者在非UI線程中使用。 
Android提供了Invalidate方法實現界面刷新,但是Invalidate不能直接在線程中調用,因爲他是違背了單線程模型:Android UI操作並不是線程安全的,並且這些操作必須在UI線程中調用。 

  Android程序中可以使用的界面刷新方法有兩種,分別是利用Handler和利用postInvalidate()來實現在線程中刷新界面。 

1,利用invalidate()刷新界面 
  實例化一個Handler對象,並重寫handleMessage方法調用invalidate()實現界面刷新;而在線程中通過sendMessage發送界面更新消息。 
 

// 在onCreate()中開啓線程

 

new Thread(new GameThread()).start();、

 

複製代碼

// 實例化一個handler

Handler myHandler = new Handler() {
// 接收到消息後處理
public void handleMessage(Message msg) {
  switch (msg.what) {
    case Activity01.REFRESH:
      mGameView.invalidate(); // 刷新界面
      break;
  }

  super.handleMessage(msg);
}
};

class GameThread implements Runnable {
  public void run() {
    while (!Thread.currentThread().isInterrupted()) {
      Message message = new Message();
      message.what = Activity01.REFRESH;
      // 發送消息
      Activity01.this.myHandler.sendMessage(message);
      try {
          Thread.sleep(100);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
  }
}

}

複製代碼

 



 

2,使用postInvalidate()刷新界面 
使用postInvalidate則比較簡單,不需要handler,直接在線程中調用postInvalidate即可。 
 

複製代碼

class GameThread implements Runnable { 
    public void run() { 
    while (!Thread.currentThread().isInterrupted()) { 
        try { 
            Thread.sleep(100); 
        } catch (InterruptedException e) { 
    Thread.currentThread().interrupt(); 
  } 

  // 使用postInvalidate可以直接在線程中更新界面 
  mGameView.postInvalidate(); 
  } 
} 
}

複製代碼

 

View 類中postInvalidate()方法源碼如下,可見它也是用到了handler的:
 

複製代碼

public void postInvalidate() {
        postInvalidateDelayed(0);
}
public void postInvalidateDelayed(long delayMilliseconds) {
        // We try only with the AttachInfo because there's no point in invalidating
        // if we are not attached to our window
        if (mAttachInfo != null) {
            Message msg = Message.obtain();
            msg.what = AttachInfo.INVALIDATE_MSG;
            msg.obj = this;
            mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
        }
    }

複製代碼

 

除了onCreate()是運行在UI線程上的,其實其他大部分方法都是運行在UI線程上的,其實其實只要你沒有開啓新的線程,你的代碼基本上都運行在UI線程上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章