In a small game without threads, I want to refresh the time progress and use timer. So I wrote a piece of code:
Nstartroundtime = system. currenttimemillis ();
Nt1 = new timer ();
Nt1.schedule (New timertask () {// scheduled run Interval
Public void run (){
Refreshtimepaint (); // call refreshtimepaint () in 3 seconds ()
}
);
Public void refreshtimepaint (){
Invalidate (); // use invalidate (); refresh
System. Out. println (system. currenttimemillis ());
System. Out. println (ngamestate );
}
At the same time, I printed system. currenttimemillis () on The View.
After running the command, it is not as expected. The results of system. Out. println are changed in the log, but the view does not respond. Not only is the view not refreshed, but even the original Touch Screen events are not reflected.
I checked it online and got some explanations:
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 "logoff" 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.
So I changed the refreshtimepaint () code:
Public void refreshtimepaint (){
This. postinvalidate (); // use postinvalidate (); refresh
System. Out. println (system. currenttimemillis ());
System. Out. println (ngamestate );
}
In this way, the view will be automatically refreshed ~~~
Here are several web pages for reference:
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