首页 > 白话Cocoa > 阻止OSX系统睡眠

阻止OSX系统睡眠

1、在OSX开发中,我们的程序怎么样获取系统睡眠或者唤醒的通知,并对程序做出一定的处理?
可以通过cocoa的API来获取,如下所示:
- (void) receiveSleepNote: (NSNotification*) note
{
    NSLog(@"receiveSleepNote: %@", [note name]);
}

- (void) receiveWakeNote: (NSNotification*) note
{
    NSLog(@"receiveWakeNote: %@", [note name]);
}
 
- (void) fileNotifications
{
    //These notifications are filed on NSWorkspace's notification center, not the default
    // notification center. You will not receive sleep/wake notifications if you file
    //with the default notification center.
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
            selector: @selector(receiveSleepNote:)
            name: NSWorkspaceWillSleepNotification object: NULL];

    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
            selector: @selector(receiveWakeNote:)
            name: NSWorkspaceDidWakeNotification object: NULL];
}
2、在程序里面怎么阻止系统睡眠?很多场景下,我们希望程序可以阻止系统睡眠。比如正在下载文件的时候,如果用挂机系统自动睡眠就会中断下载。
我们可以通过IO Kit来阻止系统睡眠,如下所示:
...
#import <IOKit/pwr_mgt/IOPMLib.h>
...

// kIOPMAssertionTypeNoDisplaySleep prevents display sleep,

// kIOPMAssertionTypeNoIdleSleep prevents idle sleep

//reasonForActivity is a descriptive string used by the system whenever it needs

//  to tell the user why the system is not sleeping. For example,

//  "Mail Compacting Mailboxes" would be a useful string.

//  NOTE: IOPMAssertionCreateWithName limits the string to 128 characters.

CFStringRef* reasonForActivity= CFSTR("Describe Activity Type");

IOPMAssertionID assertionID;

IOReturn success = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,

                                    kIOPMAssertionLevelOn, reasonForActivity, &assertionID);

if (success == kIOReturnSuccess)

{

    //Add the work you need to do without

    //  the system sleeping here.

    success = IOPMAssertionRelease(assertionID);

    //The system will be able to sleep again.

}

...
注意:
(1)、即便是通过I/O kit,也没办法阻止用户强制系统睡眠,只能阻止系统空闲睡眠。强制系统睡眠,发生在下面这些情况:用户强制执行系统菜单的睡眠菜单,盖上笔记本的盖子,电池没电等。而系统空闲睡眠是用户没有进行任何操作系统空闲了一段时间后根据能源设置项的设置而进行的睡眠。
(2)、kIOPMAssertionTypeNoDisplaySleep模式下,显示器跟系统都不睡眠
kIOPMAssertionTypeNoIdleSleep模式下,显示器会睡眠,系统不睡眠。对于kIOPMAssertionTypeNoIdleSleep 这种模式,屏幕睡眠了,系统不睡眠,程序还是运行着的。但屏幕睡眠,我们看不到程序是否在运行,这时可以通过每秒打一个日志来进行测试。
3、下面附带一个阻止系统睡眠的例子,并通过打日志来测试kIOPMAssertionTypeNoIdleSleep 模式,日志保存在/tmp/ 目录
参考资料:

https://developer.apple.com/library/mac/qa/qa1340/_index.html

(转载本站文章请注明出处 www.helloitworks.com ,请勿用于任何商业用途)

分类: 白话Cocoa 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.