invalidate()与postInvalidate()都是用来请求重绘UI的,但是invalidate()方法只能在UI线程调用,
postInvalidate()方法可以在非UI线程调用,代码如下:
invalidate();
Handler myHandler = new Handler() {
// 接收到消息后处理
public void handleMessage(Message msg) {
switch (msg.what) {
case MainActivity.REFRESH:
// 刷新界面
mGameView.invalidate();
break;
}
}
};
class GameThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Message message = new Message();
message.what = MainActivity.REFRESH;
// 发送消息
MainActivity.this.myHandler.sendMessage(message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
postInvalidate();
class GameThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 使用postInvalidate可以在非UI线程中更新界面
mGameView.postInvalidate();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}