我的 cocoa 应用程序运行后台任务,我想在用户空闲时停止(没有键盘/鼠标输入),然后在用户再次激活时恢复。有没有办法注册空闲状态通知?

最佳答案

如果您无法链接到 Carbon(即您想编译 x86_64 位二进制文​​件),您可以将此函数(以秒为单位返回当前空闲时间为 double - CFTimeInterval)包装在计时器中:

#include <IOKit/IOKitLib.h>

CFTimeInterval CFDateGetIdleTimeInterval() {
    mach_port_t port;
    io_iterator_t iter;
    CFTypeRef value = kCFNull;
    uint64_t idle = 0;
    CFMutableDictionaryRef properties = NULL;
    io_registry_entry_t entry;

    IOMasterPort(MACH_PORT_NULL, &port);
    IOServiceGetMatchingServices(port, IOServiceMatching("IOHIDSystem"), &iter);
    if (iter) {
        if ((entry = IOIteratorNext(iter))) {
            if (IORegistryEntryCreateCFProperties(entry, &properties, kCFAllocatorDefault, 0) == KERN_SUCCESS && properties) {
                if (CFDictionaryGetValueIfPresent(properties, CFSTR("HIDIdleTime"), &value)) {
                    if (CFGetTypeID(value) == CFDataGetTypeID()) {
                        CFDataGetBytes(value, CFRangeMake(0, sizeof(idle)), (UInt8 *) &idle);
                    } else if (CFGetTypeID(value) == CFNumberGetTypeID()) {
                        CFNumberGetValue(value, kCFNumberSInt64Type, &idle);
                    }
                }
                CFRelease(properties);
            }
            IOObjectRelease(entry);
        }
        IOObjectRelease(iter);
    }

    return idle / 1000000000.0;
}

您需要将您的代码链接到 IOKit.framework

关于objective-c - Objective-C : Get notifications about a user's idle state,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4643579/

10-16 10:56