Detailed process for Android to implement timed tasks

  • 2020-10-23 21:12:50
  • OfStack

In Android development, tasks are performed regularly in the following three ways:

1. sleep(long) method based on Handler and thread (java implementation is not recommended)

2. Adopt postDelayed(Runnable, long) method of Handler (the simplest android implementation)

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

There are times in android that you have to loop through a certain piece of code, or you have to execute a certain piece of code at a certain point in time, and that's a requirement that you might think of the Timer object at the first time, right, but there are better alternatives.

1. Timer realizes timing task


Timer timer;
void onCreate(){
 ......
TimerTask task = new TimerTask(){ 
public void run(){ 
 //  Add the executed code here  
} 
}; 
timer = new Timer(); 
timer.schedule(task, 1000);// Turn on the timer, delay 1s After the implementation task 
}
void onDestroy(){
......
timer.cancel();// Destruction timer 
}

2. Handler realizes timing task

1. Perform an operation after 1 period of time, and 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  
  handler.postDelayed(this, 50);// 50ms After the implementation this , i.e., runable 
  } 
 }; 
 handler.postDelayed(runnable, 50);//  Turn on the timer, 50ms After the implementation runnable operation  
}
void onDestroy(){ 
 ......
 handler.removeCallbacks(this);//  Turn off timer processing  
}

2. Perform an operation once after a certain period of time. After the execution, it will not be performed again:


void onCreate(){ 
......
Handler handler = new Handler();  
 Runnable runnable = new Runnable(){ 
 @Override 
 public void run() { 
  // TODO Auto-generated method stub  
  //  Add the executed code here  
              doSomeThing();
  handler.removeCallbacks(this); // Remove timing task  
   }  
 }; 
 handler.postDelayed(runnable, 50);//  Turn on the timer, 50ms After the implementation runnable 
}

3. AlarmManager realizes accurate timing operation

When we use Timer or handler, we find that delay is not so accurate. If we need a strict and timely timing operation, then WE need to use AlarmManager. AlarmManager object can be used with Intent. One Activity can be opened regularly, one BroadCast can be sent, or one Service can be opened regularly.

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

Performs an operation after a specified length of time


//  The following code is << Instant football score >> Code snippet in .
 public static AlarmManagerUtil{
   public static AlarmManager getAlarmManager(Context ctx){
   return (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
  }
  /**
  *  Update the event information after the designated time ( It's like an alarm clock )
  *  Pay attention to : Receiver Remember in manifest.xml Registered in 
   * 
  * @param ctx
  */
  public static void sendUpdateBroadcast(Context ctx){
   Log.i("score", "send to start update broadcase,delay time :"+);
   larmManager am = getAlarmManager(ctx);
    //  A broadcast will be produced in seconds , The trigger UpdateReceiver The implementation of the , This method is really the main code for updating the data 
   Intent i = new Intent(ctx, UpdateReceiver.class); 
   PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, , i, );
   am.set(AlarmManager.RTC, System.currentTimeMillis()+, pendingIntent)
 }
  /**
  *  Cancel scheduled execution ( Like the cancellation of an alarm clock )
  * 
  * @param ctx
  */  
  public static void cancelUpdateBroadcast(Context ctx){
   AlarmManager am = getAlarmManager(ctx);
   Intent i = new Intent(ctx, UpdateReceiver.class);
   PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, , i, );
   am.cancel(pendingIntent);
  }
 }
 //  Update the broadcast receiver of the database 
 public static class UpdateReceiver extends BroadcastReceiver{
   public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, " Update score data ", Toast.LENGTH_LONG).show();
    //  Set the global timer ( The alarm clock )  Seconds after the broadcast notification this broadcast receiver triggers execution .
    //  It's the same way JavaScript In the  setTimeout(xxx,)
    AlarmManagerUtil.sendUpdateBroadcast(context);
   }
  }

Perform an operation periodically


publicstaticvoid sendUpdateBroadcastRepeat(Context ctx){
 Intent intent =new Intent(ctx, UpdateReceiver.class);
 PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, 0);
 // The start time 
 long firstime=SystemClock.elapsedRealtime();
 AlarmManager am = (AlarmManager) ctx.getSystemService(ALARM_SERVICE);
  //60 seconds 1 Cycle after cycle, sending out broadcasts 
 am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 60*1000, pendingIntent);
}

Cancel the timer


/**
 *  Cancel scheduled execution ( Like the cancellation of an alarm clock )
 * 
 * @param ctx
 */publicstaticvoid cancelUpdateBroadcast(Context ctx){
  AlarmManager am = getAlarmManager(ctx);
  //  Note when canceling UpdateReceiver.class Must be with Settings when 1 to , That's the only way to cancel correctly 
  Intent i = new Intent(ctx, UpdateReceiver.class); 
  PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, i, 0);
  am.cancel(pendingIntent);
 }
}

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


Related articles: