Sathish Kumar k k
Sathish Kumar k k

Reputation: 1842

How to Detect workstation/System Screen Lock in ubuntu using java?

I'm trying to note down workstation/System screen lock of each employee working in ubuntu OS. I needed to store these record in a DataBase. using JAVA. I have searched all over and got on idea for UBUNTU; But got idea how to do the same in windows OS.

Upvotes: 1

Views: 2804

Answers (2)

Ortwin Angermeier
Ortwin Angermeier

Reputation: 6183

From here:

gnome-screensaver-command -q | grep "is active"

Use the Runtime class to execute that command and read back the result.

EDIT: use grep -q

Here an example how to use it:

public class ScreenSaver {

  /*
   * Pipes are a shell feature, so you have to open a shell first.
   * 
   * You could use process.getInputStream() to read the output and parse it.
   * 
   * For productive use i would prefer using the Inputstream.
   */

  private static final String COMMAND = "gnome-screensaver-command -q |  grep -q 'is active'";

  private static final String[] OPEN_SHELL = { "/bin/sh", "-c", COMMAND };

  private static final int EXPECTED_EXIT_CODE = 0;


  public static boolean isScreenSaverActive() {
    final Runtime runtime = Runtime.getRuntime();
    Process process = null;
    try {
      /*
       * open a shell and execute the command in that shell
       */
      process = runtime.exec(OPEN_SHELL);
      /*
       * wait for the command to finish
       */
      return process.waitFor() == EXPECTED_EXIT_CODE;
    } catch(final IOException e) {
      e.printStackTrace();
    } catch(final InterruptedException e) {
      e.printStackTrace();
    }
    return false;
  }


  public static void main(final String[] args) {
    System.out.println("Screensaver is active: " + isScreenSaverActive());
  }

}

EDIT: added perl script watching dbus signals. Source: Gnome Screensaver FAQ

#!/usr/bin/perl

my $cmd = "dbus-monitor --session \"type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'\"";

open (IN, "$cmd |");

while (<IN>) {
    if (m/^\s+boolean true/) {
        print "*** Screensaver is active ***\n";
    } elsif (m/^\s+boolean false/) {
        print "*** Screensaver is no longer active ***\n";
    }
}

Upvotes: 3

viki.omega9
viki.omega9

Reputation: 335

Try having a look here, ( Similar duplicate), Detect workstation/System Screen Lock using Python(ubuntu))

GNOME Screensaver FAQ This should be an awesome reference for you to get up to speed. I suppose you are using GNOME.

Upvotes: 1

Related Questions