views:

1238

answers:

4

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?)

The method should allow the program to prompt users to save, etc., and then continue the logoff process.

A: 

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.

Zan Lynx
+1  A: 

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

laz
+4  A: 

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.

R. Bemrose
A: 

You can schedule a Thread to be run on JVM shutdown - see

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)

avalys