SoFunction
Updated on 2025-04-10

Detailed explanation of the process of implementing timing tasks on Android

In Android development, tasks are executed regularly through the following three methods:

1. Use the sleep(long) method of Handler and thread (not recommended to use, Java implementation method)

2. Use Handler's postDelayed(Runnable, long) method (the simplest android implementation)

3. Use the method of combining Handler with timer and TimerTask (it is recommended for more tasks)

Sometimes in Android, a certain piece of code needs to be executed regularly, or a certain piece of code needs to be executed at a certain point in time. This requires that everyone will think of the Timer object as soon as possible. Yes, but we have better choices.

1. Timer implements timing tasks

Timer timer;
void onCreate(){
 ......
TimerTask task = new TimerTask(){ 
public void run(){ 
 // Add the executed code here} 
}; 
timer = new Timer(); 
(task, 1000);//Open the timer and execute task after delaying for 1s}
void onDestroy(){
......
();//Destroy the timer}

2. Handler implements timing tasks

1. Execute an operation after a period of time and execute it in a loop:

void onCreate(){ 
 ......
 Handler handler = new Handler(); 
 Runnable runnable = new Runnable(){ 
  @Override 
  public void run() { 
  // TODO Auto-generated method stub 
  // Add the executed code here  (this, 50);// Execute this after 50ms, that is, runable  } 
 }; 
 (runnable, 50);// Turn on the timer and execute the runnable operation after 50ms}
void onDestroy(){ 
 ......
 (this);// Turn off timer processing}

2. Execute an operation once every once a while, and after execution, it will no longer be executed:

void onCreate(){ 
......
Handler handler = new Handler();  
 Runnable runnable = new Runnable(){ 
 @Override 
 public void run() { 
  // TODO Auto-generated method stub  
  // Add the executed code heredoSomeThing();
  (this); //Remove timing tasks   }  
 }; 
 (runnable, 50);// Turn on the timer and execute runnable after 50ms}

3. AlarmManager implements accurate time operation

When we use Timer or handler, we will find that the delay time is not that accurate. If we need a strictly and punctual timing operation, we need to use AlarmManager. The AlarmManager object can be used in conjunction with Intent, and can be enabled regularly, a BroadCast is sent, or a Service is enabled.

The following code introduces the use of two timing methods in detail:

Perform an action after a specified duration

// The following code is a code snippet in <<Football Live Score>>. public static AlarmManagerUtil{
   public static AlarmManager getAlarmManager(Context ctx){
   return (AlarmManager) (Context.ALARM_SERVICE);
  }
  /**
   * Update event information after the specified time (such as the alarm clock setting)
   * Note: Receiver remember to register in
    *
   * @param ctx
   */
  public static void sendUpdateBroadcast(Context ctx){
   ("score", "send to start update broadcase,delay time :"+);
   larmManager am = getAlarmManager(ctx);
    // A broadcast will be generated in seconds, triggering the execution of UpdateReceiver. This method is the main code of real update data operation.   Intent i = new Intent(ctx, ); 
   PendingIntent pendingIntent = (ctx, , i, );
   (, ()+, pendingIntent)
 }
  /**
   * Cancel timing execution (such as cancellation of alarm clock)
   *
   * @param ctx
   */  
  public static void cancelUpdateBroadcast(Context ctx){
   AlarmManager am = getAlarmManager(ctx);
   Intent i = new Intent(ctx, );
   PendingIntent pendingIntent = (ctx, , i, );
   (pendingIntent);
  }
 }
 // Update the broadcast receiver of the database public static class UpdateReceiver extends BroadcastReceiver{
   public void onReceive(Context context, Intent intent) {
    (context, "Update score data", Toast.LENGTH_LONG).show();
    // Set the global timer (alarm clock) and send a broadcast notification to the broadcast receiver to trigger execution after seconds.    // This method is very similar to setTimeout(xxx,) in JavaScript    (context);
   }
  }

Perform an operation periodically

publicstaticvoid sendUpdateBroadcastRepeat(Context ctx){
 Intent intent =new Intent(ctx, );
 PendingIntent pendingIntent = (ctx, 0, intent, 0);
 //Start time long firstime=();
 AlarmManager am = (AlarmManager) (ALARM_SERVICE);
// One cycle of 60 seconds, constantly sending broadcasts (AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 60*1000, pendingIntent);
}

Cancel the timer (alarm clock)

/**
  * Cancel timing execution (such as cancellation of alarm clock)
  *
  * @param ctx
  */publicstaticvoid cancelUpdateBroadcast(Context ctx){
  AlarmManager am = getAlarmManager(ctx);
  // When canceling, please note that it must be consistent with the setting time, so that the cancellation must be correctly cancelled.  Intent i = new Intent(ctx, ); 
  PendingIntent pendingIntent = (ctx, 0, i, 0);
  (pendingIntent);
 }
}

The above is a detailed explanation of the Android timing task process introduced by the editor. I hope you like it.