【问题标题】:Notification when the system is idle or not on OS X系统空闲或不在 OS X 上时的通知
【发布时间】:2011-06-20 22:14:51
【问题描述】:

我知道有一些方法可以在 OS X 上使用 IOKit 框架来获取系统空闲时间,但我想知道是否有可用的通知。

我可以创建一个计时器来检查空闲时间是否超过 x,这很好。几秒后检测到空闲模式也没关系。

问题是检测 Mac 何时不再空闲。我希望我的应用程序尽快显示通知,而不是几秒钟后。

有没有办法对此进行通知? (iChat 好像有)

【问题讨论】:

  • 我已经测试了NSWorkspaceScreensDidWakeNotification,只要从空闲返回的定义与唤醒显示器相同,它就可以工作。除此之外,您可能必须安装一个事件点击来检测鼠标/键盘事件,将它们解释为从空闲状态返回。
  • @Bavarious 将此作为答案。
  • 我不知道 Cocoa 和 Objective C 之间是否有区别,但是Objective C: Get notifications about a user's idle state 的答案可能会有所帮助。

标签: macos cocoa notifications


【解决方案1】:

来自http://developer.apple.com/library/mac/#qa/qa1340/_index.html(来自蜥蜴比尔评论)

- (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】:
    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-05
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 2014-11-05
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多