Reputation: 237
I'm new to Java
and Android
, I would like to set up a time counter in my ACTION_UP
event and cancel the timer while I do the other events. How can I basically set up a timer for that and stop and reset the timer for other event?
Upvotes: 1
Views: 1690
Reputation: 8562
For the CountDownTimer
Here I've started 30 seconds of time ticker like
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();
}
Method Description
CountDownTimer(long millisInFuture, long countDownInterval)
millisInFuture
= Time in milliseconds
countDownInterval
= Interval in millisecond
Now you can use these methods For other kind of operation.
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.`
Upvotes: 2
Reputation: 6142
Timer start time.
Set this in start timer click event.
Date startDate = new Date();
long startTime = 0;
startTime = startDate.getTime();
Store startTime in Global Variable so you can use that variable later.
Timer end time.
Set this in stop timer click event.
Date endDate = new Date();
long endTime = 0;
endTime = endDate.getTime();
Now get time difference in millisecond.
long timeDiff = endTime - startTime;
Upvotes: 1
Reputation: 151
You have to try this
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;
}
You have to write the handler inside this code and reset the handler on other events. code for handler
new Handler().postDelayed(new Runnable() {
public void run() {
//Your Task
}
}, TIME);
Upvotes: 0