I was making an application in Java and I was wondering if there was any way to know if when I run this application from the shortcut, it detects that it is already running and opens that process for me as it happens with the Spotify desktop application.
I have found a "homemade" method to know if it is already running; I save the current time with Java.util.Calendar.getTimeInMillis()
in a notepad every x seconds, if when trying to open the application from a direct access the time saved in the txt is less than x it means it is running and it would not open another copy. With this I make sure that it can only be opened once, but I would like it not only to be able to do that but also to find that process and send it to the front.
There is no specific method, but a common workaround in swing is to apply
frame.setAlwaysOnTop(true);
and right afterframe.setAlwaysOnTop(false);
to bring it to the fore. This, applied together with the method that detects if the application is open, will give you the expected result.Another method would be to use one
ManagementFactory
that only allows one instance of the application as explained here .Another little thing:
I see the method well, that is:
it is not necessary to write every
X
second, only the first time when starting, so you can free resources.Hello, a simple solution is through a ServerSocket. First it is to create the server socket, assign a port to it, and catch the Exception, here you could treat the exception so that it adapts to what you propose (if this exception occurs you can terminate your program or throw it to the front (maximize) because the other is already there running there). But you have to choose the port well so that it is not something that another program is going to use.
Top display: