在一個沒有使用線程的小遊戲中想重新整理一下時間進度,想到用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