开发者

Notification when the system is idle or not on OS X

I know that there is some way to get the system idle time with the IOKit framework on OS X, but I want to know if there's notifications available.

I can create a timer to check if the idle time is more than x, and that's fine. It doesn't matter if I detect the idle mode a few seconds later.

The problem is to detect when the Mac is not idle anymore. I wa开发者_C百科nt my app to show a notification as soon as possible, not a few seconds later.

Is there a way to have a notification for that? (iChat seems to have one)


This is from http://developer.apple.com/library/mac/#qa/qa1340/_index.html (from Bill the Lizard comment)

- (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];
}


NSTimeInterval GetIdleTimeInterval() {

    io_iterator_t iter = 0;
    int64_t nanoseconds = 0;

    if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IOHIDSystem"), &iter) == KERN_SUCCESS) {
        io_registry_entry_t entry = IOIteratorNext(iter);
        if (entry) {
            CFMutableDictionaryRef dict;
            if (IORegistryEntryCreateCFProperties(entry, &dict, kCFAllocatorDefault, 0) == KERN_SUCCESS) {
                CFNumberRef obj = CFDictionaryGetValue(dict, CFSTR("HIDIdleTime"));
                if (obj)
                    CFNumberGetValue(obj, kCFNumberSInt64Type, &nanoseconds);
                CFRelease(dict);
            }
            IOObjectRelease(entry);
        }
        IOObjectRelease(iter);
    }

    return (double)nanoseconds / 1000000000.0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜