0

I wanted to write a program in Java which listens the event from mac os, when electric power goes off and battery mode starts.

I am not getting any lead in this direction.

Hrishikesh Mishra
  • 3,295
  • 3
  • 27
  • 33

1 Answers1

1

I don't think Java has any predefined library functions for this behavior, but here's an idea: create a background thread that periodically checks whether the power is plugging in via pmset(1). That thread can then kick something else off.

For example, the following will cause the program to exit if AC power is not plugged in. You can extend this however you need.

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import java.util.logging.Level;

public class BatteryPower {

    private static int INTERVAL = 1000;

    private static void batteryPoller() {
        while (true) {
            try {
                // spawn process and check stdin
                Process proc = Runtime.getRuntime().exec("pmset -g ps");
                BufferedReader stdin = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                String s = stdin.readLine();
                if (s != null && !s.contains("AC Power"))
                    System.exit(0);

                // cleanup and wait
                stdin.close();
                proc.destroyForcibly();
                Thread.sleep(INTERVAL);
            }
            catch (IOException|InterruptedException e) {
                Logger.getLogger(BatteryPower.class.getName()).severe(e.toString());
                // consider exiting or changing INTERVAL here
            }
        }
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                batteryPoller();
            }
        };

        new Thread(r).start();
        // main exits, but process doesn't exit until this thread exits.
    }
}

This only works for macOS. Checkout this answer for Windows. (My answer is partly based on that one.)

Sagar
  • 1,617
  • 9
  • 17