最佳答案
多次运行 jar 意味着启动多个应用程序(和 JVM),并且每个 Java 应用程序都有一个 SystemTray
实例。
来自SystemTray
javadoc:
Every Java application has a single SystemTray instance that allows the app to interface with the system tray of the desktop while the app is running. T
因此,您应该使用主策略来检测应用程序是否已经运行,或者更简单地阻止应用程序运行多次。
创建一个服务器套接字,并在应用程序启动时绑定(bind)到特定端口(例如使用 ServerSocket
实例)是一种简单的方法。
以下是检测到抛出异常的示例:
public static void main(String[] args) {
assertNoOtherInstanceRunning();
... // application code then
}
public static void assertNoOtherInstanceRunning() {
new Thread(() -> {
try {
new ServerSocket(9000).accept();
} catch (IOException e) {
throw new RuntimeException("the application is probably already started", e);
}
}).start();
}
关于java - 如何检测托盘是否已经运行或禁用多次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49674277/