Reputation: 63
I have some doubts I had in mind regarding a section of code that I retrieved from some answers given which were used to prevent the user from clicking the same button multiple times. Can someone explain to me what this section code does and give examples?
The Codes are
private long mLastClickTime = 0;
//Avoid the user clicking more than one
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
the if condition is placed below every button.setonclicklistener
I just want to understand what this section of code does only :)
Upvotes: 5
Views: 16161
Reputation: 806
I'll explain it using more detailed variable names.
private long mLastClickTime = 0;
private long theUserCannotClickTime = 1000; // milliseconds. the time that must pass before the user's click become valid
long currentTime = SystemClock.elapsedRealtime(); // not necessarily the current realworld time, and it doesn't matter. You can even use System.currentTimeMillis()
long elapsedTime = currentTime - mLastClickTime; // the time that passed after the last time the user clicked the button
if (elapsedTime < theUserCannotClickTime)
return; // 1000 milliseconds hasn't passed yet. ignore the click
}
// over 1000 milliseconds has passed. do something with the click
// record the time the user last clicked the button validly
mLastClickTime = currentTime;
Upvotes: 8
Reputation: 2004
elapsedRealtime() and elapsedRealtimeNanos() return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.
For futher check this method
https://developer.android.com/reference/android/os/SystemClock.html#elapsedRealtime()
Upvotes: 2