Four ways to implement timers in Android
The first way to make use of timer and TimerTask
1. Inheritance Relationship
Java.util.Timer
Basic methods
Schedule
For example:
Timer.schedule (task, delay,period);
Delay is long,period long: Once delay milliseconds from now on, it is performed every period milliseconds.
The schedule method has three parameters
The first parameter is the object of the TimerTask type, and our implementation of the TimerTask run () method is a task to be performed periodically;
The second parameter has two types, the first is a long type, indicating how long it starts and the other is the date type, which indicates that execution begins after that time;
The third parameter is the period of execution, which is a long type.
2,
TimerTask task= New TimerTask () {
@Override public
void Run () {
count++;
LOG.I ("Mainactivity", Count + "");
}
};
Here are several ways to schedule tasks:
Time is a date type: Executes once at a specified period.
Timer.schedule (task, time);
Firsttime is a date type and period is long, which is executed every period millisecond from firsttime time.
timer.schedule (task, firsttime,period);
Delay is long: delay milliseconds from now to execute once.
timer.schedule (task, delay);
Delay is long,period long: Once delay milliseconds from now on, it is performed every period milliseconds.
timer.schedule (task, delay,period);
Note: The task should be canceled in Ondestory (), or a crash may occur
3, with timertask timing of some operation of the app, even if the exit, TimerTask will still run for a while, but can not run for a long time
The second way of using Countdowntimer
1, Demo
Countdowntimer CDT = new Countdowntimer (10000) {@Override public
void Ontick (long millisuntilfinished) {
Tv_hello.settext (millisuntilfinished + "");
}
@Override public
void OnFinish () {
}
};
Cdt.start ();
2, the above example is
Execute the Ontick method once every 100 milliseconds
The method in OnFinish () will be executed until the end of the 10000/100-time execution.
The Third Way of Alarmmanager
Demo
Intent Intent2 = newintent (readlogservice.this,testbroadcast.class);
Pendingintent PD =pendingintent.getbroadcast (getapplicationcontext (), 0, intent2,pendingintent.flag_one_shot);
Alarmmanager am = (alarmmanager) getsystemservice (alarm_service);
Long Triggertime =systemclock.elapsedrealtime () + 5*1000;
Am.set (Alarmmanager.elapsed_realtime,triggertime, PD);
The fourth way of Alarmmanager
handler.sendemptymessagedelayed (0, 4000);//Start Handler, implement 4 seconds timed loop execution
Private Handler handler = new Handler () {
Public voidhandlemessage (Android.os.Message msg) {
if (ischange) {
//logical processing
Handler.sendemptymessagedelayed (0,4000);//4 seconds after execution
}}
;
Thank you for reading, I hope to help you, thank you for your support for this site!