Detect OS Sleep and Wake Up events in Java

前端 未结 3 404
礼貌的吻别
礼貌的吻别 2020-12-16 18:40

Is there a way for a Java program to detect when the operating system is about to go to sleep, or failing that, at least detecting a wake up?

The actual problem is t

相关标签:
3条回答
  • 2020-12-16 18:46

    I know it's not exactly what you're looking for, but maybe the right answer is to try to write the code with the assumption that your sockets won't necessarily stay up. There are lots of reasons why the connection could crash, for example because the DB is taken down for maintenance, or because someone tripped over your Ethernet cable. I think you'd have similar problems with errors if someone pulled out the network cable while your app was running, and these are not unheard-of conditions, so maybe it's a better approach to try and handle those conditions gracefully.

    0 讨论(0)
  • 2020-12-16 18:59

    You could detect the wakeup by periodically comparing the current system time to the previous system time.

    Edit: here's an example that looks like it would help you detect when the machine is going to sleep: http://www.codeguru.com/cpp/w-p/system/messagehandling/article.php/c6907

    0 讨论(0)
  • 2020-12-16 19:04

    You could just JNI or JNA to trap the sleep/wakeup events from the OS.

    From Windows Power Events (MSDN), you would have to create a Window handler and a null window to receive the WM_POWERBROADCAST events. This window procedure could then call an event function in your Java code to bubble the message up.

    0 讨论(0)
提交回复
热议问题