Reputation: 3296
My question might be a common requirement. Unfortunately haven't found a proper guide on it anywhere.
I require to set a timeout in software in Java. In my setup I have a mouse attached to an Android device.
Basically my Android application has two modes: ENGAGED and DISENGAGED.
By default, the application resides in DISENGAGED mode.
The app shows different screens in ENGAGED and DISENGAGED mode, which gets automatically controlled based upon the mode.
Now to enter ENGAGED mode, the user is expected to perform a left click of the mouse. The app remains in engaged mode as long as the user uses the mouse. If the user doesn't use the mouse for a period of 30 seconds, the APP goes back to DISENGAGED mode.
While in software I receive events for every touch that the user performs, obviously I don't get any event when the 30 seconds have passed since the last touch. Thus I need a proper solution for going back to disengaged mode.
How does one implement this in software? A basic outline of the code flow should suffice, need not be an exact working code. I am comfortable using semaphores, tasks, mutexs, etc.
Upvotes: 0
Views: 237
Reputation: 523
All you need to do is start up a simple thread that waits 30 seconds and resets whenever mouse movement is detected.
It is generally recommended to implement Runnable instead of extending Thread since Java only has single inheritance. Here's a runnable private class that should work:
private static class CustomRunnable implements Runnable{
@Override
public void run() {
boolean waiting = true;
while(waiting){
try {
Thread.sleep(30000);
waiting = false;
// went 30 seconds with no interrupt - go to sleep mode
} catch (InterruptedException e) {
waiting = true;
// we were interrupted by mouse movement - restart loop
}
}
}
}
You can start the thread using
Thread sleepThread = new Thread(new CustomRunnable());
sleepThread.start();
And you can reset the thread using
sleepThread.interrupt();
Upvotes: 2
Reputation: 688
Won't this do the trick: System.currentTimeInMillis() API for currentTimeMillis()
Upvotes: 0