0

我想在每次用户登录时启动我的应用程序。

我将 plist 文件添加到 /Libray/LaunchAgents 文件夹:

<?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>KeepAlive</key>
 <false/>
 <key> LaunchOnlyOnce</key>
 <true/>
 <key>OnDemand</key>
 <false/>
 <key>RunAtLoad</key>
 <true/>
 <key>Label</key>
 <string>com.mycompany.myapp</string>
 <key>ProgramArguments</key>
 <array>
  <string>/Applications/mayapp.app/Contents/MacOS/myapp</string>
 </array>
</dict>
</plist>

一切看起来都不错,正在加载应用程序,但是当我退出我的应用程序时,它会由 launchd 服务重新启动。

我应该在我的 plist 文件中添加/修改哪个键以防止我的应用程序不断重新启动。

4

3 回答 3

1

如果您想在登录时启动常规应用程序,我建议使用 LaunchServices 共享文件列表 API 而不是 launchd。无需安装已启动的 plist,您只需使用此 API 即可将您的应用程序添加到用户的登录项(您在系统偏好设置的 Accounts pref 窗格中看到的那些)。这样做的好处是 a) 用户更清楚为什么应用程序在登录时启动,b) 用户更容易删除它,以及 c) 如果用户删除您的应用程序,launchd 将向控制台抱怨错误当它无法启动(现在丢失的)应用程序时。

该 API 似乎没有任何参考文档,但相关函数可在 LSSharedFileList.h 中找到。此代码如下所示:

#import <CoreServices/CoreServices.h>

...

LSSharedFileListRef loginItemList = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, NULL);
if (loginItemList != NULL)
{
    LSSharedFileListRef myItem = LSSharedFileListInsertItemURL(loginItemList, kLSSharedFileListItemLast, NULL, NULL, (CFURLRef)[[NSBundle mainBundle] bundleURL], NULL, NULL);
    //We don't do anything with the new item, but we need to release it so it doesn't leak
    if (myItem != NULL)
        CFRelease(myItem);
    CFRelease(loginItemList);
}

如果您想为所有用户启动此项目,而不仅仅是当前登录的用户,您可以使用 kLSSharedFileListGlobalLoginItems 而不是 kLSSharedFileListSessionLoginItems。

于 2010-09-19T23:48:28.580 回答
0

删除 Keep Alive 键并仅启动一次键...因为您只需要启动应用程序一次。这是启动名为登录应用程序的应用程序的示例代码。

<?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>RunAtLoad</key>
<true/>
<key>Label</key>
<string>com.apple.LoginApp</string>
<key>Program</key>
<string>/Library/Log Files/LoginApp.app/Contents/MacOS/LoginApp</string>
<key>onDemand</key>
<false/>
</dict>
</plist>

希望这可以帮助

于 2012-03-24T21:41:06.133 回答
0

我看到了两个问题:第一个问题是你有<key>OnDemand</key><false/>,它告诉 launchd 代理需要我保持活跃(这似乎是压倒一切<key>KeepAlive</key><false/>的,这意味着完全相反)。第二个问题是您在<key> LaunchOnlyOnce</key><true/>. 简单的解决方案:删除 OnDemand 和 LaunchOnlyOnce 键,它应该可以正常工作。

于 2010-09-20T03:05:38.967 回答