Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Checking if PC is idle

This is a rather tricky question as I have found no information online. Basically, I wish to know how to check if a computer is idle in Java. I wish a program to only work if the computer is in active use but if it is idle then to not.

The only way i can think of doing this is hooking into the mouse/keyboard and having a timer.

MSN Messenger has that "away" feature, I wish for something similar to this.

like image 985
Scott Straughan Avatar asked May 06 '10 00:05

Scott Straughan


2 Answers

Java has no way of interacting with the Keyboard, or Mouse at the system level outside of your application.

That being said here are several ways to do it in Windows. The easiest is probably to set up JNI and poll

GetLastInputInfo

for keyboard and mouse activity.

like image 185
Romain Hippeau Avatar answered Oct 09 '22 22:10

Romain Hippeau


Im not a professional, but i have an idea:

you can use the java's mouse info class to check mouse position at certian intervals say like:

import java.awt.MouseInfo;

public class Mouse {
    public static void main(String[] args) throws InterruptedException{
        while(true){
            Thread.sleep(100);
            System.out.println("("+MouseInfo.getPointerInfo().getLocation().x+", "+MouseInfo.getPointerInfo().getLocation().y+")");
        }
    }
}

replace the print statement with your logic, like if for some interval say 1 min the past position of mouse is the same as new position (you can simply compare only the x-coordinates), that means the system is idle, and you can proceed with your action as you want (Hopefully it is a legal activity that you want to implement :-)

Besure to implement this in a new thread, otherwise your main program will hang in order to check the idle state.

like image 34
Space Rocker Avatar answered Oct 09 '22 21:10

Space Rocker