SoFunction
Updated on 2025-03-11

Android   Simple application and precautions for TimerTask

Simple application and precautions for Android TimerTask

Timers are often used in Android application development, and it is inevitable that TimerTask timer task class is used.

The following is a simple example that demonstrates how to use TimerTask

This example demonstrates that if there is no touch screen event in 3 seconds, the lock screen will be locked (just set the following text, meaning it). If there is a touch screen event, the lock will be unlocked.

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 textView;
 private Handler mHandler;
 private Timer mTimer;
 private MyTimerTask mTimerTask;
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView();
    
    textView = (TextView)findViewById();
    
    mHandler = new Handler(){
     public void handleMessage(Message message){
     (TAG, "message what = " + );
     if ( == 0x100){
      lockWindow();
     }
     
     }
    };
    
    mTimer = new Timer(true);
    
    resumeWindow();
    
    StartLockWindowTimer();
  }
  
  public boolean onTouchEvent(MotionEvent event)
  {
   // TODO Auto-generated method stub
   resumeWindow();
   StartLockWindowTimer();
   
   return (event);
  }
  
  public void resumeWindow(){
   ("main window");
 
  }
  
  public void lockWindow(){
   ("lock window");
  }
  
  public void StartLockWindowTimer(){
   if (mTimer != null){
   if (mTimerTask != null){
    (); //Remove the original task from the queue   }
   
   
   mTimerTask = new MyTimerTask(); // Create a new task   (mTimerTask, 3000);
   }
  }
  
  class MyTimerTask extends TimerTask{
 @Override
 public void run() {
  // TODO Auto-generated method stub
  (TAG, "run...");
  Message msg = (EVENT_LOCK_WINDOW);
  ();
 }
   
  }
}

There are two issues to be noted here:

 if (mTimerTask != null){
      (); //Remove the original task from the queue   }

Before each timed task is released, make sure that the previous task has been removed from the timer queue.

 mTimerTask = new MyTimerTask(); // Create a new task  

Every time you place a task, you have to create a new object, otherwise an error will occur:

      ERROR/AndroidRuntime(11761): : TimerTask is scheduled already

So the same timer task can only be placed once

Thank you for reading, I hope it can help you. Thank you for your support for this site!