一、CountDownTimer
CountDownTimer countDownTimer = new CountDownTimer(24 * 60 * 60 * 1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
long day = millisUntilFinished / (1000 * 24 * 60 * 60);
long hour = (millisUntilFinished - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60);
long minute = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60);
long second = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000;
Log.d("TAG", String.format("剩余时间:%d时%d分%d秒", hour, minute, second));
}
@Override
public void onFinish() {
}
};
countDownTimer.start();
countDownTimer.cancel();
二、handler.postDelayed
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
@Override
public void run() {
Log.d("TAG", "run: ");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
handler.removeCallbacks(runnable);
三、Handler + Timer + TimerTask
private Timer timer = new Timer();
private Handler handler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("TAG", "handleMessage: timer");
}
};
TimerTask task = new TimerTask() {
@Override
public void run() {
Message msg = handler.obtainMessage();
msg.what = 1;
msg.obj = "";
msg.sendToTarget();
}
};
timer.schedule(task, 1000, 2000);
timer.cancel();
四、Handler + Thread.sleep()
private Handler handler = new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d("TAG", "handleMessage: ");
}
};
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
Message msg = handler.obtainMessage();
msg.what = 1;
msg.obj = "";
msg.sendToTarget();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();