Timer is often used in Android Application Development. timertask timer tasks are inevitable.
The following simple example demonstrates how to use timertask
This example demonstrates that if no touch screen event occurs in 3 seconds, the lock will be unlocked if there is a touch screen event (just set the text, meaning ).
Public Class Coltimertaskactivity Extends Activity {
/** Called when the activity is first created. */
Private Final String tag = "coltimertaskactivity ";
Private Final Int Event_lock_window = 0x100;
Private Textview;
Private Handler mhandler;
Private Timer mtimer;
Private Mytimertask mtimertask;
@ Override
Public Void Oncreate (bundle savedinstancestate ){
Super . Oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Textview = (textview) findviewbyid (R. Id. textview );
Mhandler = New Handler (){
Public Void Handlemessage (message ){
Log. I (TAG, "message what =" + message. What );
If (Message. What = 0x100 ){
Lockwindow ();
}
}
};
Mtimer = New Timer (True );
Resumewindow ();
Startlockwindowtimer ();
}
Public Boolean Ontouchevent (motionevent event)
{
// Todo auto-generated method stub
Resumewindow ();
Startlockwindowtimer ();
Return Super . Ontouchevent (event );
}
Public Void Resumewindow (){
Textview. settext ("Main Window ");
}
Public Void Lockwindow (){
Textview. settext ("lock window ");
}
Public Void Startlockwindowtimer (){
If (Mtimer! = Null ){
If (Mtimertask! = Null ){
Mtimertask. Cancel (); // Remove the original task from the queue
}
Mtimertask = New Mytimertask (); // Create a task
Mtimer. Schedule (mtimerjob, 3000 );
}
}
Class Mytimertask Extends Timertask {
@ Override
Public Void Run (){
// Todo auto-generated method stub
Log. I (TAG, "Run ...");
Message MSG = mhandler. obtainmessage (event_lock_window );
MSG. sendtotarget ();
}
}
}
Pay attention to the following two issues:
If(Mtimertask! =Null){
Mtimertask. Cancel ();//Remove the original task from the queue
}
Make sure that the previous task has been removed from the timer queue before each scheduled task is placed.
Mtimertask =NewMytimertask ();//Create a task
You must create a new object for each task. Otherwise, an error occurs:
Error/androidruntime (11761): Java. Lang. illegalstateexception: timertask is scheduled already
Therefore, the same timer task can only be placed once.