1.最簡單的計時
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 2000);
2.計時和循環(huán)
Runnable mRun;
Handler handler = new Handler();
private void setTimer2(){
mRun = new Runnable() {
@Override
public void run() {
//做的操作
}
};
//想再次調(diào)用時可以調(diào)這個方法
handler.postDelayed(mRun, 5000);
//這個是注銷這個計時
handler.removeCallbacks(mRun);
}
3.計時和循環(huán)
Timer timer;
private void setTimer3(){
timer = new Timer(false);
timer.schedule(new TimerTask() {
//此方法是在子線程中執(zhí)行的
@Override
public void run() {
//更新時間
//調(diào)回主頁
TimeActivity.this.runOnUiThread(new TimerTask() {
@Override
public void run() {
//取消定時任務(wù)和界面操作
timer.cancel();
}
});
}
}, 0, 1000);
}
4.獲取當前時間的2中方法
private void getData1(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
// HH:mm:ss獲取當前時間
Date date = new Date(System.currentTimeMillis());
tvTime.setText("Date獲取當前日期時間:::"+simpleDateFormat.format(date));
}
private void getData2(){
Time mTime=new Time();
mTime.setToNow(); // 取得系統(tǒng)時間。
int year = mTime.year;
int month = mTime.month+1;
int day = mTime.monthDay;
int hour = mTime.hour;
int minute = mTime.minute;
int second = mTime.second;
tvTime2.setText("獲取當前日期:"+year+"年"+month+"月"+day+"月\n "+hour+"時:"+minute+"分:"+second+"秒");
}