mac系统开机启动实现

来源:互联网 发布:手机放大字体软件 编辑:程序博客网 时间:2024/06/02 06:11

在mac系统的sandbox环境下,要设置开机启动就不能使用sharedFileList,apple公司推介使用helper小程序来启动主程序。

实现的简要步骤:
1、在xcode中设计一个简单的Cocoa程序,姑且命名为BootLaunchHelper;
2、设置helper程序的参数:
Build Settings>Skip Install属性设置为 YES;
Info>Custom OS X Application Target Properties>Application is agent(UI Element)属性设置为YES;
Info>Custom OS X Application Target Properties>Application is background only属性设置为YES.
3、在主程序中,将helper程序打包到主程序的Contents/Library/LoginItems目录下.
3.1 在xcode主程序中,需要在Build Phases中新建Copy Files属性,然后设置属性:
Copy Files>Destination : Wrapper
Copy Files>Subpath : Contents/Library/LoginItems
添加xxxhelper程序。这样在build你的主程序时就可以直接将helper程序打包进指定的目录。
3.2 在xcode主程序中还需要引用系统包,在Build Phases>Link Binary With Libraries中添加系统库ServiceManagement.framework.
头文件中包含ServiceManagement/ServiceManagement.h文件。
3.3 在Qt程序中,可以将设置函数封装为Library,同样在Library中也要和主程序一样的设置。
4、注册helper程序为开机启动程序
以下代码放在xcode主程序设置开机启动的地方,或Qt程序设计开机启动的调用Library中。

    // 注册启动程序路径到ServerManage    OSStatus res = LSRegisterURL((__bridge CFURLRef)[NSURL fileURLWithPath:helperPath], true);    if (res != noErr) {        NSLog(@"Regist launch app failed.");        return -2;    }    // 设置或禁止启动程序开机启动    if (!SMLoginItemSetEnabled((__bridge CFStringRef)appId, bEnable)) {        NSLog(@"SetEnabled launch app failed.");        return -3;    }

5、在Mac下由于注册使用路径和identify标志两种形式,如果在不同的path都注册了同样的identify程序,就会在ServiceManagement的path数据库添加多个启动程序,会导致系统可能找不到正确的启动路径。解决方法就是将多余的拷贝路径删除。
下面这行命令显示BootLaunchHelper.app程序所有可用的路径:

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -dump|grep .*path.*BootLaunchHelper

删除多余的拷贝路径:

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user
0 0