我该如何在Mac OS X上以编程方式设置应用程序捆绑包,以便在用户登录时运行?
基本上,这相当于Windows中的HKCU\Software\Microsoft\Windows\CurrentVersion\Run
注册表键。
下面是一个可行的示例。
创建一个文件
~/Library/LaunchAgents/my.everydaytasks.plist
其内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>my.everydaytasks</string>
<key>ProgramArguments</key>
<array>
<string>/Applications/EverydayTasks.app/Contents/MacOS/EverydayTasks</string>
</array>
<key>ProcessType</key>
<string>Interactive</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
</dict>
</plist>
看看原来帮助我制作这个示例的帖子:
https://superuser.com/a/229792/43997
要进行测试,您需要在终端中运行此命令。
launchctl load -w ~/Library/LaunchAgents/my.everydaytasks.plist
卸载
launchctl unload -w ~/Library/LaunchAgents/my.everydaytasks.plist
另请参阅
这是使用“登录项”将应用程序添加到启动项的另一种方式。请参考此示例项目了解如何实现:
“正确”的方法是针对您想要在登录时启动的具有用户界面的进程创建LaunchAgent,并为那些应该是纯后台进程的进程创建LaunchDaemon。 在您的安装程序中,将您的plist文件放入正确的文件夹中,可以是针对用户、所有用户或系统。 这种方法优越的原因在于您可以使用launchd控制您的进程运行方式,包括内置功能,确保即使进程崩溃或被用户终止,它也会继续运行。
如果您使用Qt / C ++,想要使用plist文件,那么可以通过QSettings类轻松实现。以下是一个示例虚拟应用程序的代码片段。
void MainWindow::readPlist()
{
QSettings settings(appPlistPath, QSettings::NativeFormat);
QVariant value = settings.value("mykey");
QMessageBox::information(this, "Your Value", value.toString());
}
void MainWindow::addPlistEntry()
{
QSettings settings(appPlistPath, QSettings::NativeFormat);
settings.setValue("mykey", "myvalue");
}
void MainWindow::removePlistEntry()
{
QSettings settings(appPlistPath, QSettings::NativeFormat);
settings.remove("mykey");
}
osascript
。下面是实现的方法:struct LaunchAtStartupHelper {
static var isEnabled: Bool {
get {
shell(
"""
osascript -e 'tell application "System Events" to get the name of every login item'
""")
.contains("MyAppName")
}
set {
if newValue {
shell(
"""
osascript -e 'tell application "System Events" to make login item at end with properties {path:"/Applications/MyAppName.app", hidden:true}'
""")
} else {
shell(
"""
osascript -e 'tell application "System Events" to delete login item "MyAppName"'
""")
}
}
}
// from https://dev59.com/TV8d5IYBdhLWcg3wTQwn#50035059
@discardableResult
private static func shell(_ command: String) -> String {
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
return output
}
}
man launchd.plist
以获取plist格式的官方(并且最新)文档。 - Barry Wark