小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

android中Invalidate和postInvalidate的區(qū)別

 little_catgirl 2013-06-05

android中Invalidate和postInvalidate的區(qū)別

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

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

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

// 在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;
// 發(fā)送消息
Activity01.this.myHandler.sendMessage(message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

}

2,使用postInvalidate()刷新界面
使用postInvalidate則比較簡單,不需要handler,直接在線程中調(diào)用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的:
  1. public void postInvalidate() {
  2.         postInvalidateDelayed(0);
  3. }

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



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

 

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多