Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 want 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)

like image 394
gcamp Avatar asked Jun 20 '11 22:06

gcamp


2 Answers

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];
}
like image 166
Paulo Casaretto Avatar answered Sep 22 '22 14:09

Paulo Casaretto


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;
}
like image 26
Mike Glukhov Avatar answered Sep 24 '22 14:09

Mike Glukhov