如何在Java中检测macOS笔记本电脑是否处于睡眠状态

huangapple go评论57阅读模式
英文:

How to detect macOS laptop is sleeping in Java

问题

问题:在Mac笔记本电脑上运行Java客户端,当Mac进入睡眠模式时(例如,当盖子关闭时),我的客户端的"pingServer"线程成功地向服务器发送了一个ping请求数据包(我在服务器上看到了ping请求数据包),但是当盖子关闭时,我们没有收到响应(可以理解)。

我想要检测MacBook Pro笔记本电脑何时进入睡眠模式,以便我可以中断ping线程,直到Mac不再处于睡眠状态。

我看到Desktop类中有一个"SystemSleepListener",但我没有找到任何实现的代码示例。

如何在Java中检测macOS的睡眠模式?

英文:

Problem:
Running Java client on a Mac Laptop, When the Mac goes into sleep mode (for example when the lid is closed), my client "pingServer" thread successfully sends a ping request packet to the server (I see the ping request packet in the server), however when the lid is closed, we do not receive a response. (Understandably)

I want to detect that the MacBook Pro laptop is going to sleep or is sleeping, so I can interrupt the ping thread until the Mac is no longer sleeping.

I have seen a "SystemSleepListener" in the Desktop class, but I have not found any code examples of implementation.

How can I detect macOS sleep mode in Java?

答案1

得分: 4

这应该是可能的,而不使用仅在Apple Java中可用的类:

import java.awt.Desktop;

Desktop desktop = Desktop.getDesktop();
SystemSleepListener systemSleepListener = new SystemSleepListener() {

	@Override
	public void systemAboutToSleep(SystemSleepEvent e) {
		System.out.println("Going to sleep");
	}

	@Override
	public void systemAwoke(SystemSleepEvent e) {

	}

};
desktop.addAppEventListener(systemSleepListener);

请注意,某些平台不支持 SystemSleepListener。您可以通过调用以下方式来检查是否支持:

desktop.isSupported(Desktop.Action.APP_EVENT_SYSTEM_SLEEP)
英文:

This should be possible without using classes only available in Apple Java:

import java.awt.Desktop;

Desktop desktop = Desktop.getDesktop();
SystemSleepListener systemSleepListener = new SystemSleepListener() {

	@Override
	public void systemAboutToSleep(SystemSleepEvent e) {
		System.out.println("Going to sleep");
	}

	@Override
	public void systemAwoke(SystemSleepEvent e) {

	}

};
desktop.addAppEventListener(systemSleepListener);

Note that some platforms do not support SystemSleepListener. You can check if it is supported by calling

desktop.isSupported(Desktop.Action.APP_EVENT_SYSTEM_SLEEP)

huangapple
  • 本文由 发表于 2023年3月31日 21:46:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75899271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定