Home>

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

First, use the handler and thread sleep (long) method (not recommended,java implementation)

Second, using the handler's postdelayed (runnable, long) method (the simplest android implementation)

Third, the combination of handler and timer and timertask (recommended for more tasks)

In Android, it is sometimes necessary to periodically execute a certain piece of code.Or need to execute a piece of code at a certain point in time,This demand everyone will think of the timer object for the first time, yes, but we have better options.

First, the timer implements timing tasks

timer timer;
void oncreate () {
 ...
timertask task=new timertask () {
public void run () {
 //add executed code here
}
};
timer=new timer ();
timer.schedule (task, 1000);//Enable the timer,execute task after delay 1s
}
void ondestroy () {
...
timer.cancel ();//Destroy the timer
}

Second, the handler implements timing tasks

1. Perform an operation after a period of time,Loop execution:

void oncreate () {
  ...
  handler handler=new handler ();
  runnable runnable=new runnable () {
   @override
   public void run () {
    //todo auto-generated method stub
    //add executed code here
    handler.postdelayed (this, 50);//This is executed after 50ms, that is, runable
   }
  };
  handler.postdelayed (runnable, 50);//turn on the timer,Runnable after 50ms
}
void ondestroy () {
 ...
 handler.removecallbacks (this);//turn off timer processing
}

2. Perform an operation once in a while,After execution,No longer execute:

void oncreate () {
...
handler handler=new handler ();
 runnable runnable=new runnable () {
 @override
 public void run () {
   //todo auto-generated method stub
   //add executed code here
Dosomething ();
   handler.removecallbacks (this);//Remove scheduled tasks
     }
 };
 handler.postdelayed (runnable, 50);//turn on the timer,Runnable after 50ms
}

Third, alarmmanager realizes precise timing operation

When we use timer or handler, we will find thatThe delay time is not so accurate.If we need a strictly punctual timing operation,Then you need to use alarmmanager, alarmmanager object with intent use, you can start an activity at regular intervals, send a broadcast, or start a service.

The following code details the use of two timing methods:

Perform an action after a specified duration

//The following code is a snippet from<< Football Live Score >>.
 public static alarmmanagerutil {
     public static alarmmanager getalarmmanager (context ctx) {
     return (alarmmanager) ctx.getsystemservice (context.alarm_service);
   }
   /**
    * Update the event information after a specified time (like the setting of an alarm clock)
   * Note:The receiver remembers to register in manifest.xml
     *
   * @param ctx
   * /
   public static void sendupdatebroadcast (context ctx) {
     log.i ("score", "send to start update broadcase, delay time:" +);
     larmmanager am=getalarmmanager (ctx);
       //Broadcast will be generated in seconds,Trigger the execution of updatereceiver, this method is the main code to update 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 cancellation of 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 database broadcast receiver
 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 (alarm clock) to send a broadcast notification after 2 seconds to trigger the broadcast receiver to execute.
       //This method is much like settimeout (xxx,) in javascript
       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);
 //Starting time
 long firstime=systemclock.elapsedrealtime ();
 alarmmanager am=(alarmmanager) ctx.getsystemservice (alarm_service);
//60 seconds a cycle,Keep sending broadcasts
 am.setrepeating (alarmmanager.elapsed_realtime_wakeup, firstime, 60 * 1000, pendingintent);
}

Cancel timer (alarm clock)

/**
 * Cancel scheduled execution (like cancellation of alarm clock)
 *
 * @param ctx
 */publicstaticvoid cancelupdatebroadcast (context ctx) {
   alarmmanager am=getalarmmanager (ctx);
   //Please note that updatereceiver.class must be consistent with the setting when canceling,So that you can cancel it 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 timer task process we introduced to you.Hope you like it.

  • Previous PHP method to achieve static HTML page
  • Next EditText method to limit text input in Android programming