Java: Handle logoff or shutdown on Windows and Linux

后端 未结 4 1970
面向向阳花
面向向阳花 2021-01-06 04:13

Is there a way for a Java GUI application to respond to system shutdown or logoff events, other than to use JNI? (On Windows, the JNI would use WM_QUERYENDSESSION, on Linux

相关标签:
4条回答
  • 2021-01-06 04:36

    You can schedule a Thread to be run on JVM shutdown - see addShutdownHook().

    0 讨论(0)
  • 2021-01-06 04:43

    As far as I know, there's no way in Java to catch the system shutdown or logoff events.

    You can, however, catch when the JVM is terminating by adding a shutdown hook.

    AWT's WindowAdapter also has a windowClosing event that you can override and hook to a window that you want to monitor. Swing inherits this; I believe SWT does as well. Be aware that you MUST manually dispose of the window if you override this event!

    I believe that MS Windows will fire these events as it is closing. I believe a SIGTERM on Linux/UNIX does the same, although Linux will SIGKILL an app shortly afterwords if this is during shutdown.

    0 讨论(0)
  • 2021-01-06 04:49

    I think that Runtime.getRuntime().addShutdownHook should provide the functionality you need.

    0 讨论(0)
  • 2021-01-06 04:51

    This doesn't answer the question, but addresses part of it.

    In a Unix GUI session, I consider the right way to handle the logoff event is to save the document to a temporary file and save the information in the session state. During the session recovery, the program can reload the temporary file and take up where it left off. No need to ask the user about saving or not.

    I just wish more software did transparent session save and recovery. Too many programs reopen with empty document windows because the GUI framework used does that much but none of the rest of the work has been done to actually handle any meaningful program state.

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