Question

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?

Was it helpful?

Solution

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;
}

OTHER TIPS

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();

If you just need to see if the method has been called within the last 3 seconds you can use a Handler and a Boolean flag to acomplish this.

private Handler mHandler = new Handler();
private boolean wasRun = false;

mHandler.postDelayed(new Runnable() {

    @Override
    public void run() {
        if(wasRun){               
           //whatever you want to do if run
        }
        mHandler.postDelayed(this, 3000);
    }
 },3000); //3 sec

In this example the Handler will run on a 3 second delay. Each time it runs it will check to see if the other method was perviously called by evaluating if(wasRun). This way you can change what happens if the method was/was not called. The handler will then start iself again on another 3 second delay. All you have to do then is update the wasRun flag to be true if your method was called, or false if it was not. .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top