Run Jar file on startup?

2019-04-15 14:17发布

问题:

I have a Java application that lives in the system tray that I compile to a executable jar file. I would like to add the option within my program to add to the system startup items.

As I do not know of any uniform way to do this for all operating systems I assumed I would have to write code to do it for each one I intend to support so I started with Windows.

When I attempted to add it to the registry at [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] using the code available here I discovered that under Windows 7 and 8 unless I have administrator privileges (by running from an elevated command prompt) my edits to the registry do not apply.

Then I spent a day trying to figure out how to get the Jar to relaunch itself with admin privileges before I gave up on that hacky workaround.

Can the task I'm trying to achieve even be accomplished and if so how?

回答1:

For the most part, you're actually looking to add the feature of auto starting on user login, rather than on system startup. For windows, if you add the registry entry under:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

This location does not suffer from permissions issues when run as an ordinary user, and has been supported for a long time under Windows (I'm thinking Windows 95 time frame here), so should be a safe change across all systems.

For Linux, assuming that the operating system is following the Open Desktop AutoStart specification, then you need to create the appropriate .desktop file in $HOME/.config/autostart/ and it should autostart on login in that case.

For Mac OS X, you need to create a launch agent plist in $HOME/Library/LaunchAgents. The Daemons and services documentation details how to construct this file.



回答2:

Working around user privileges is not a good idea. The registry entry is the preferred way to go. Also keep in mind that the jar by itself is not executable, it requires the jvm, so what you might want to do is use a wrapper and register that.