I wrote an android timer last night and started to think it was easy. I wrote it in Java and found that the timer couldn't run at all, but no error was reported. I stayed there, I don't know what to do. Later I checked it online. Considering the thread security issue, Android does not allow the thread to execute the UI thread in the thread (as I know now, there are other restrictions). In Android, there is an interesting class: Android. OS. handler, which can realize message transmission between threads.
Segment first
Code In this example, a handler is instantiated. handler can communicate with multiple threads through message. What I am doing here is timed reclen plus 1, and then in a certain format, display to rectime (operations on the UI thread ).
Code
1 Final Handler = New Handler (){
2 Public Void Handlemessage (Message MSG ){
3 Switch (Msg. What ){
4 Case 1 :
5 Reclen ++ ;
6 Rectime. settext (getrectime (reclen ));
7 Break ;
8 }
9 Super . Handlemessage (MSG );
10 }
11 };
The following is a timertask, which provides a scheduled task for timer. I added a message sending function to handler in this method, because it is not allowed to directly operate the UI thread in the timer thread. 1 Timertask task = New Timertask (){
2 Public Void Run (){
3 Message message = New Message ();
4 Message. What = 1 ;
5 Handler. sendmessage (Message );
6 }
7 };
The rest of the work is much simpler. Adding a timer can make Program Running 1 Timer = New Timer ( True );
2 Timer. Schedule (task, 1000 , 1000 ); // Execution after 1 ms delay, 1 ms execution
3 // Timer. Cancel (); // Exit Timer
Speaking of this, I may still feel confused in the cloud. I haven't written anything for a long time, and I don't know how to make the problem clearer. I will post the incorrect writing method I started and compare it with the wrong writing method, it may make everyone better understand it. Incorrect syntax
1 Timertask task = New Timertask () {
2 Public Void Run () {
3Reclen++;
4Rectime. settext (getrectime (reclen ));//The UI thread is operated directly in timertask. During single-step debugging, the program is not executed here.
5}
6 } ;
7 Timer = New Timer ( True );
8 Timer. Schedule (task, 1000 , 1000 );
Note: I am also a beginner in Android. If you say something wrong, you are welcome to correct me. I would like to talk to you more here. When a learning process encounters problems, I feel really helpless.