我是Java
和Android
的新手,我想在我的ACTION_UP
事件中设置一个计时器,并在执行其他事件时取消计时器。我如何基本上为此设置计时器,并停止并重置其他事件的计时器?
对于CountDownTimer
,我已经启动了类似的30秒时间跟踪器
CountDownTimer countDownTimer;
TextView tvTicker = (TextView) findViewById(R.id.tvTicker);
public void startClicked(View view) { //When button start is clicked
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
tvTicker.setText("seconds remaining: " + millisUntilFinished / 1000);
//Do some stuff here for saving the duration to a variable or anything else as your requirements
}
public void onFinish() {
tvTicker.setText("done!");
}
}.start();
}
方法描述
CountDownTimer(long millisInFuture, long countDownInterval)
millisInFuture
=以毫秒为单位的时间
countDownInterval
=以毫秒为单位的间隔
现在您可以将这些方法用于其他类型的操作。
countDownTimer.cancel(); //Cancel the countdown.
countDownTimer.onFinish() //Callback fired when the time is up.
countDownTimer.onTick(long millisUntilFinished); //Callback fired on regular `interval. millisUntilFinished is The amount of time until finished.`
计时器开始时间
在启动计时器单击事件中设置此项。
Date startDate = new Date();
long startTime = 0;
startTime = startDate.getTime();
将startTime存储在全局变量中,以便以后可以使用该变量。
计时器结束时间
在停止计时器点击事件中设置此项。
Date endDate = new Date();
long endTime = 0;
endTime = endDate.getTime();
现在获得毫秒内的时差。
long timeDiff = endTime - startTime;
你必须尝试这个
public boolean onTouchEvent(MotionEvent event) {
boolean touch;
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
touch = false;
break;
case MotionEvent.ACTION_UP:
touch = true;
// Code for Timer
break;
}
return true;
}
您必须在该代码中编写处理程序,并在其他事件中重置处理程序。处理机代码
new Handler().postDelayed(new Runnable() {
public void run() {
//Your Task
}
}, TIME);