在一个没有使用线程的小游戏中想刷新一下时间进度,想到用Timer。于是写了一段代码:
nStartRoundTime = System.currentTimeMillis();
nT1 = new Timer();
nT1.schedule(new TimerTask(){ //计划运行时间间隔
public void run(){
refreshTimePaint(); //过3秒调用一下refreshTimePaint()
}
},0,3000);
public void refreshTimePaint(){
invalidate(); //使用invalidate();刷新
System.out.println(System.currentTimeMillis());
System.out.println(nGameState);
}
同时我也将System.currentTimeMillis()打印在View上。
运行一下,发现并不是预期那样, System.out.println的结果在Log里面都有变化,但是View却没有反应。 不但View上面没有被刷新,甚至连原来的触屏事件都没有反映了。
去网上查了一下,得到的一些解释有这些:
The best thing is to use Handler with delayed messages.
And Timer works fine, the problem is that a Timer runs in a separate thread, and so you are trying to modify a view owned by another thread (the main thread that originally created it).
What I think is happening is you're falling off the UI thread. There is a single "looper" thread which handles all screen updates. If you attempt to call "invalidate()" and you're not on this thread nothing will happen.
Try using "postInvalidate()" on your view instead. It'll let you update a view when you're not in the current UI thread.
于是把refreshTimePaint()的代码改成:
public void refreshTimePaint(){
this.postInvalidate(); //使用postInvalidate();刷新
System.out.println(System.currentTimeMillis());
System.out.println(nGameState);
}
这样View就能自动刷新了~~~
这里有几个网页做参考:
http://stackoverflow.com/questions/522800/android-textview-timer
http://groups.google.com/group/android-developers/browse_thread/thread/5baf5a3eaa823b7b?pli=1
http://groups.google.com/group/android-developers/msg/f5765705b8c59d66