Reputation: 321
I'm new to Android and I'm working on a tiny project with a set of strict parameters. One of them is to have a multifunction button that increments a timer every time it's clicked, and that starts only after I didn't increment said timer for 3 seconds.
I found three or four ways on how to set an alarm of sorts with Handler
, CountDownTimer
, Timer
, or some other way, but I'm confused on how I can do what I'm looking for with just the onClick()
method.
The function to wait for 3s(), I'm calling it after:
public void wait3s()
{
Thread thread = new Thread() {
@Override
public void run()
{
while (!isInterrupted()) {
try {
Thread.sleep(3000);
runOnUiThread(new Runnable() {
@Override
public void run() {
count++;
threeS.setText(String.valueOf(count));
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
}
My onClick()
just calls these:
public void onClick(View view)
{
increment();
wait3s();
startStop();
}
As you can see, part of the issue is that I'm calling the wait3s()
there at every click, and I need a way to control that Thread/Timer (whatever) without it creating a new one at every click. I'm being a little dumb now, but I have been on this for a while and I'm still coming out empty, since I never worked with this before.
Another option for the wait3s()
function that I found would be like in this other StackOverflow thread.
Thank you
PS: Sorry for the title, I couldn't find a better way to describe it, if you have it, and have the power to change it, please do.
Upvotes: 1
Views: 98
Reputation: 321
Here's how I solve it. Although the suggestions were closer, they weren't exactly spot on to what I was looking for, in terms of logic, they weren't exactly helpful, creating more issues. Perhaps it's due to my explanation of the problem, perhaps because I'm new to Android Studio and the explanations shared here with me. Pardon me if it looks like I'm just using my own answer for internet points, I just had to put a lot more to understand this by myself than what I actually got from the answers shared here.
public void wait3s()
{
t.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
startStop();
}
});
}
}, 3000);
}
The variable t
is a Timer(), and I had to import the classes java.util.Timer
, and java.util.TimerTask
. I called this method inside my increment()
method and under onClick()
I just have the increment()
method. Turned out pretty neat.
Upvotes: 0
Reputation: 390
Handler.removeCallbacks will effectively cancel a runnable.
boolean timerStarted = false;
clockHandler = new Handler();
OnClick(){
if (!timerStarted){
incrementTimer();
clockHandler.removeCallbacks(null);
clockHandler.postDelayed(new Runnable() {
@Override
public void run() {
// maybe kick off another handler/runnable here to start your timer
timerStarted = true;
}
}
}, 3 * 60 * 1000);
} else {
startStop();
}
}
Upvotes: 1