问题
Possible Duplicate:
How to programmatically prevent a Mac from going to sleep?
What is the correct method on the current version of OS X (10.7) for preventing sleep while an application or process is running?
In particular, is IOCancelPowerChange
still (or did it ever) serve this purpose? I call IOCancelPowerChange
in response to kIOMessageCanSystemSleep
, but that doesn't do the trick.
Essentially the same question as the first part of this one has been asked before, but the documentation it points to is quite old and the answer was never accepted.
回答1:
IOCancelPowerChange
continues to work but only for idle triggered sleep; it will not work for sleep triggered by the Finder's Sleep menu item, programmatically requested, or from a push of the power button.
Apple's Q&A1340 answers the question "Q: How can my application get notified when the computer is going to sleep or waking from sleep? How do I prevent sleep?"
Listing 2 of Q&A1340:
#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.
}
Note that you can only stop idle time sleep, not sleep triggered by the user.
For applications supporting Mac OS X 10.6 and later, use the new IOPMAssertion family of functions. These functions allow other applications and utilities to see your application's desire not to sleep; this is critical to working seamlessly with third party power management software.
回答2:
You could call updatesystemActivity(OverallAct) every 30 seconds to prevent the display from sleeping.
来源:https://stackoverflow.com/questions/8460033/what-is-the-correct-way-to-prevent-sleep-on-os-x