【发布时间】:2021-08-02 12:22:52
【问题描述】:
我想用 Java 编写一个程序,当电源关闭和电池模式启动时,它会监听来自 mac os 的事件。
我没有在这个方向上取得任何领先。
【问题讨论】:
标签: java events operating-system event-handling macos-catalina
我想用 Java 编写一个程序,当电源关闭和电池模式启动时,它会监听来自 mac os 的事件。
我没有在这个方向上取得任何领先。
【问题讨论】:
标签: java events operating-system event-handling macos-catalina
我认为 Java 没有针对这种行为的任何预定义库函数,但这里有一个想法:创建一个后台线程,定期检查电源是否通过 pmset(1) 插入。然后该线程可以启动其他内容。
例如,如果没有插入交流电源,以下将导致程序退出。您可以根据需要扩展它。
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.
}
}
这仅适用于 macOS。结帐this answer 用于 Windows。 (我的回答部分基于那个。)
【讨论】: