Search code examples
javasleepscreensaverstandby

Java - Put screen to sleep (or screensaver)


I'm currently writing a program for our local fire department to display the firetrucks that have to be occupied, the destination of the alarm etc.

The program itself is written in Java and runs on a raspberry pi connected to a TV screen. In order to protect the screen from staying on the same site and content and prevent the screen from burning in I want to put the screen into sleep or turn the screensaver on when the alarm is over (command will be sent over TCP, but that's not the problem). I also want to turn the screen back up when a new alarm is received.

I have not been able to find a solution that will put the screen to sleep or screensaver, and get it back up again. Has anyone done something like this?


Solution

  • Unfortunately, Java does not have a built-in library for this. However, you can do

    Runtime.getRuntime().exec("xscreensaver-command -activate");
    

    To deactivate the screensaver, do

    Runtime.getRuntime().exec("xscreensaver-command -deactivate");
    

    Also, make sure xscreensaver is installed

    sudo apt-get install xscreensaver
    

    I don't know if this will help reduce the heat from the screen, but you could try

    public class ScreenSaver {
        private static final JFrame frame = new JFrame();
    
        public static void startScreenSaver() throws Exception {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
             frame.setBackground(Color.BLACK);
             frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
             frame.setResizable(false);
             frame.setUndecorated(true);
             frame.validate();
             GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(frame);
             frame.setVisible(true);
        }
    
        public static void stopScreenSaver() {
             frame.setVisible(false);
        }
    }