android Four ways to realize timer in
The first way to use Timer and TimerTask
1. Inheritance relationship
java.util.Timer
Basic methods
schedule
For example:
timer.schedule(task, delay,period);
//Delay is long,period is long: after delay milliseconds from now on, it is executed every period milliseconds.
The schedule method has three parameters
The first parameter is the object of TimerTask type. Our implementation of the run() method of TimerTask is a task to be executed periodically;
The second parameter has two types. The first is long, which indicates how long it will take to start execution. The other is Date, which indicates when it will start execution;
The third parameter is the execution cycle, which is of type long.
2,
TimerTask task= new TimerTask() {
@Override
public void run() {
count++;
Log.i("MainActivity",count + "");
}
};
//Here are several ways to schedule task s:
//Time is of Date type: executed once at the specified time.
timer.schedule(task, time);
//firstTime is of Date type and period is long, which means that it is executed every period millisecond from the first time.
timer.schedule(task, firstTime,period);
//Delay is of long type: it is executed once in delay milliseconds from now on.
timer.schedule(task, delay);
//Delay is long,period is long: after delay milliseconds from now on, it is executed every period milliseconds.
timer.schedule(task, delay,period);
Note: the task should be cancelled in ondestore(), otherwise it may crash
3. An APP that uses TimerTask to perform certain operations on a regular basis. Even if it exits, it will still run for a while in TimerTask, but it cannot run for a long time
The second way is to use CountDownTimer
1,Demo
CountDownTimer cdt = new CountDownTimer(10000, 100) {
@Override
public void onTick(long millisUntilFinished) {
tv_hello.setText(millisUntilFinished + "");
}
@Override
public void onFinish() {
}
};
cdt.start();
2. The example above is
Execute methods in onTick every 100 milliseconds
Until 10000 / 100 times of execution, the method in onFinish() will be executed finally
The third way is 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 method, AlarmManager
handler.sendEmptyMessageDelayed(0, 4000);//Start the handler to implement the 4-second periodic execution
private Handler handler = new Handler(){
public voidhandleMessage(android.os.Message msg) {
if(isChange){
//Logical processing
handler.sendEmptyMessageDelayed(0,4000);//Execute again in 4 seconds
}
}
};