How would one implement some kind of background process that constantly (or in short intervals) checks if the user is interacting with the system, that is, plain and simply, using the computer? The obvious way is to check for user-generated events of any kind, such as key presses, mouse moves and mouse clicks, etcetera. It is straightforward to capture events within a certain application because those are usually automatically supplied via the application's event loop, but how does one achieve this system-wide, i.e. irrespective of what application is in front/has focus? How is this done elegantly, so such a process does not consume too much system resources?
I'm interested in this in general, but obviously there is a different way for each platform – a cross-platform way (Java) would be ideal, but my platform of choice is Mac OS X (Cocoa).