Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Creating a variable that increments once per second

In Java for Android, I want to create a variable that increases by 1 every second, in other words, it counts, that way I can check to see if a function has been called in the past 3 seconds, and if not, I want it to do something different than if it had been.

Is there any built-in way to do this? I'm familiar with the Timer class, but it doesn't seem to work the way I would want it to.. is there anything else?

tl;dr: I want to create a variable that increases by 1 every second, so I can use it to treat a function differently based on how long it has been since its last call. Is there an easy way to do this? If not, what is the hard way to do this?

like image 569
Zeldarulah Avatar asked Feb 22 '26 21:02

Zeldarulah


2 Answers

Why not store the last time the method was called instead, then check it against the current time?

private long timeLastCalled;

public void someMethod() {
    timeLastCalled = SystemClock.elapsedRealTime();
}

public boolean someMethodCalledRecently() {
    return (SystemClock.elapsedRealTime() - timeLastCalled) > 3000;
}
like image 157
Karakuri Avatar answered Feb 24 '26 10:02

Karakuri


final int[] yourVariable = new int[1];
yourVariable[0] = 0;
updateVariableTimer = new CountDownTimer(howLongYouWantTimerToLast, 1000) {
    @Override
    public void onTick(long l) {
        yourVariable[0] += 1;
    }
}.start();

Or Alternatively to do it with a flag instead of keeping track of variable counting:

final boolean functionCalledRecently = false;
hasFunctionBeenCalledRecentlyTimer = new CountDownTimer(3000, 1000) {
    @Override
    public void onTick(long l) {
        functionCalledRecently = true;
    }
    @Override
    public void onFinish() {
        functionCalledRecently = false;         
    }
}.start();
like image 20
Adam Johns Avatar answered Feb 24 '26 11:02

Adam Johns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!