开发者

Mac - Get Battery/Charging Status (Plugged in or not)

I'm building a Mac OSX app that needs to poll a server every minute, or even less if the user wishes. Unfortunately the service doesn't 开发者_Go百科support push...

Anyways, I would like to provide two options to the user:

  1. Polling interval on battery Polling
  2. interval while charging

How would I get the state of the charger in Objective C? I don't really care about the actual percentage, only if the laptop is plugged in or not. Obviously, this doesn't matter for desktops, so hopefully there is a solution that works for laptops and desktops.


Have a look at the IOPowerSources API.

First call IOPSCopyPowerSourcesInfo(), then IOPSCopyPowerSourcesList() to get a list of all available power sources. IOPSGetPowerSourceDescription() will return a dictionary with information about a particular power source. According to the documentation, the key kIOPSPowerSourceStateKey describes "the current source of power. kIOPSBatteryPowerValue indicates power source is drawing internal power; kIOPSACPowerValue indicates power source is connected to an external power source."

You can also set up a notification when the power sources change with IOPSNotificationCreateRunLoopSource().

(NB: I haven't tested any of this, just looked at the documentation.)


Although this question does already have an accepted answer which led me to my solution, it was painful to click through lots and lots of broken links.

Here is my solution:

  1. Add IOKit.framework
  2. Import #import <IOKit/ps/IOPowerSources.h>
  3. Code:

    CFTimeInterval timeRemaining = IOPSGetTimeRemainingEstimate();
    
    if (timeRemaining == kIOPSTimeRemainingUnlimited) {
            // connected to outlet
    } else if (timeRemaining == kIOPSTimeRemainingUnknown){
            // time remaining unknown (recently unplugged)
    } else if ((timeRemaining / 60) < 30){
            // less than 30 minutes remaining
    }
    
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜