Check if display is at sleep or receive sleep notifications

前端 未结 3 1585
时光说笑
时光说笑 2021-02-06 19:16

I have an application utility which becomes useless when there\'s no user. So, in order to save resources, I\'d like it to know when/whether display is at sleep.

There\'

3条回答
  •  别那么骄傲
    2021-02-06 20:03

    The DisplayWrangler service sends notifications for when the display will power off:

    // Doesn't include error checking - just a quick example
    io_service_t displayWrangler;
    IONotificationPortRef notificationPort;
    io_object_t notification;
    
    displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching("IODisplayWrangler");
    notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
    IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, NULL, ¬ification);
    
    CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
    IOObjectRelease (displayWrangler);
    

    Then the callback looks something like this:

    void displayPowerNotificationsCallback(void *refcon, io_service_t service, natural_t messageType, void *messageArgument)
    {
       switch (messageType) {
       case kIOMessageDeviceWillPowerOff :
          // This is called twice - once for display dim event, then once 
          // for display power off
          break;
       case kIOMessageDeviceHasPoweredOn :
          // Display powering back on
          break;
       }
    }
    

提交回复
热议问题