我如何从自己的应用程序中读取 MacBookPro 电池的状态?
通过谷歌搜索目前只能找到设备驱动程序处理电源事件的 API,没有关于用户空间进程访问这些信息的内容。
谢谢。
如果你想通过命令行快速查询电池状态,你会发现pmset命令很有帮助。要查询电池状态,请使用以下命令:
$ pmset -g batt
IOPSCopyPowerSourcesInfo()
获取一个数据块,然后使用IOPSCopyPowerSourcesList()
从中提取CFArray列表,列出所有电源信息。接下来,使用IOPSGetPowerSourceDescription()
提取字典(请查看IOPSKeys.h了解字典内容)。或许可以将提取的文本放入脚本应用程序中
pmset -g batt | head -n 1 | cut -c19- | rev | cut -c 2- | rev
输出
Battery Power
AC Power
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/pmset -g batt | perl -ne ' print \"$1\n\" if /([0-9]+%)/'";
NSPipe *pipe = [NSPipe pipe];
task.standardOutput = pipe;
[task launch];
NSData *data = [pipe availableData];
看看系统管理控制器。我手头没有我的MBP,但我相信你需要查看smc.h