两个术语:
- 启动项(startup item):在用户登录前就运行的item。
- 登录项(login item):在用户登录后运行的item。每个用户都有一个不同的登录项集合。
这里介绍一下登录项。
一直以来,很多开发人员希望他们的程序能在用户登录时自动运行。但长久以来,并没有相关的API实现这一点,除了一些破解手法。要做到这一点,还依赖于OS的版本。
- 对于10.5或更高版本,可以使用LaunchServices/LSSharedFileList.h中的API。
- 对于10.2或以后版本,使用苹果的LoginItemsAE示例代码(http://developer.apple.com/samplecode/LoginItemsAE/index.html)或Ulikusterer的Cocoa封装UKLoginItemRegistry(http://www.zathras.de/angelweb/sourcecode.htm#UKLoginItemRegistry)。
苹果的文档也详细介绍了多种不同的方法实现登录和登出。需要注意的是,launchd用户agent在10.4已经完全被抛弃了,应该避免使用。(http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html)。
如果想知道一个登录项是否在运行被启动了,可以参考KnowingIfAppWasLaunchedFromLoginItems。
LaunchService负责将文档绑定到引用程序,以及启动应用程序的系统级的功能。
它是ApplicationServices umbrella框架的一部分。
文档:
概念性的文档http://developer.apple.com/documentation/Carbon/Conceptual/LaunchServicesConcepts/index.html
参考引用文档http://developer.apple.com/documentation/Carbon/Reference/LaunchServicesReference/index.html
技术文档http://developer.apple.com/technotes/tn/tn2017.html
例子:
一个很简单的例子,实现了一个用在Cocoa Mac Apps中来注册/反注册自身的Controller,使用了LSSharedFileList。
使用LSSharedFileList意味着你的永和可以选则System Preferences > Accounts > Login Items。
I'm currently using it on 10.6 (32/64) successfully. I've not investigated being able to flag the "Hide" flag which is possible from System Preferences.
1、实现(Code):
1.1 需要在登录时启动app?
LaunchAtLoginController *launchController = [[LaunchAtLoginController alloc] init];
BOOL launch = [launchController launchAtLogin];
[launchController release];
1.2 设置登录状态
LaunchAtLoginController *launchController = [[LaunchAtLoginController alloc] init];
[launchController setLaunchAtLogin:YES];
[launchController release];
2、实现(Interface Builder):
- 打开Interface Builder
- 在nib窗体中放置一个NSObject(蓝色的小盒子)
- 从Inspector-Identity选项卡(Cmd+6)中设置Class到LaunchAtLoginController
- 放置一个复选框在窗体/视图上
- 从Inspector-Bindings选项卡(Cmd+4)找到Value item
- 在Login Controller绑定到Launch
- Model Key路径:launchAtLogin