接收有关笔记本电脑OSX Cocoa中电源线开/关的通知 [英] Receive notification for power cord on/off in OSX Cocoa for the laptop

查看:51
本文介绍了接收有关笔记本电脑OSX Cocoa中电源线开/关的通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部

在Mac笔记本电脑中插入/拔下电源线时,OSX是否发送任何通知吗?还是从扩展坞插入/拔出笔记本电脑?

Does OSX sends any notification when the power cord is plugged/unplugged in the Mac laptop? Or plugging/unplugging the laptop from the docking station?

它确实在关闭/重启/唤醒/等状态下发送了一些消息,但是我没有发现该特定事件的任何消息.

It does send something on shutdown/reboot/wake-up/etc, but I didn't find anything for that specific event.

我错过了什么吗?还是这不可用?

Am I missing something? Or this is not available?

TIA!

推荐答案

没有高级通知,但是只要电源状态发生变化,IOPowerSources框架就可以将消息发布到您的运行循环中.

There are no high-level notifications, but the IOPowerSources framework can post a message to your run loop whenever the power state changes.

我的项目有多个 PowerCondition 对象,它们监视当前电源的各个方面(A/C与电池,剩余电量等等).

My project has multiple PowerCondition objects that monitor various aspects of the current power (A/C vs. Battery, how much battery is left, and so on).

这是 PowerCondition 类的片段,它显示了如何通过运行循环观察电源更改事件,并将其转变为多个对象可以观察到的通知(这是相当古老的Obj-C):

Here's a fragment of the PowerCondition class that shows how to observe power source change events via the run loop and turn that into a notification that multiple objects can observe (this is fairly old Obj-C):

#define kPowerConditionChangedNotification  @"PowerConditionChanged"

static NSUInteger PowerChangeListenerCount = 0;
static CFRunLoopSourceRef PowerChangeSource = NULL;
static void PowerChangeCallback(void *context)
{
    // Called by CFRunLoopSourceRef when something changes
    // Post a notification so that all PowerCondition observers can reevaluate
    [[NSNotificationCenter defaultCenter] postNotificationName:kPowerConditionChangedNotification object:nil];
}

@interface PowerCondition
{
    BOOL listening;
    //...
}

- (void)powerStateDidChangeNotification:(NSNotification*)notification;

@end

// ...

@implementation PowerCondition

- (void)startMonitoringCondition
{
    if (!listening)
        {
        // Observe the power condition change notification
        DebugLogger(@"condition '%@'",[self description]);
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(powerStateDidChangeNotification:)
                                                     name:kPowerConditionChangedNotification
                                                   object:nil];
        if (PowerChangeListenerCount++==0)
            {
            // This is the first observer: create and install the run loop source that will fire the notification
            BetaAssert(PowerChangeSource==NULL,@"zero PowerChangeListenerCount, but PowerChangeSource!=NULL");
            PowerChangeSource = IOPSNotificationCreateRunLoopSource(PowerChangeCallback,NULL);
            CFRunLoopAddSource([[NSRunLoop mainRunLoop] getCFRunLoop],PowerChangeSource,kCFRunLoopCommonModes);
            DebugLoggerMessage(@"installed PowerChangeSource(PowerChangeCallback) in run loop");
            }

        listening = YES;
        previousTestState = -1;         // neither YES nor NO
        }
}

- (void)stopMonitoringCondition
{
    if (listening)
        {
        // Stop observing power condition change notifications
        PowerLogger(@"condition '%@'",[self description]);
        [[NSNotificationCenter defaultCenter] removeObserver:self];

        BetaAssert(PowerChangeListenerCount!=0,@"PowerChangeListenerCount==0");
        if (--PowerChangeListenerCount==0)
            {
            // This was the last power change observer: remove the run loop source the fires the notifications
            BetaAssertNotNil(PowerChangeSource);
            CFRunLoopRemoveSource([[NSRunLoop mainRunLoop] getCFRunLoop],PowerChangeSource,kCFRunLoopCommonModes);
            CFRelease(PowerChangeSource);
            PowerChangeSource = NULL;
            DebugLoggerMessage(@"removed PowerChangeSource(PowerChangeCallback) from run loop");
            }

        listening = NO;
        }

}

- (void)powerStateDidChangeNotification:(NSNotification*)notification
{
    // Evaluate power state here

    BOOL battery = NO;                                  // assume unlimited/external power
    double capacityRemaining = 1.0;                     // assume 100%

    // First, determine if the system's active power source is AC or battery
    CFTypeRef powerBlob = IOPSCopyPowerSourcesInfo();
    CFArrayRef powerSourcesRef = IOPSCopyPowerSourcesList(powerBlob);
    CFIndex count = CFArrayGetCount(powerSourcesRef);
    if (count!=0)
        {
        // There's precious little explination what the meaning of the different power sources
        //  are or why there would be more than one. As far as I can tell, everything can be
        //  determined by obtaining the first (and probably only) power source description.
        NSDictionary* powerInfo = (__bridge id)IOPSGetPowerSourceDescription(powerBlob,CFArrayGetValueAtIndex(powerSourcesRef,0));
        if (![powerInfo[@kIOPSPowerSourceStateKey] isEqualToString:@kIOPSACPowerValue])
            {
            // Power source is not AC (must be battery or UPS)
            battery = YES;
            // Calculate the remaining capacity, as a fraction
            NSNumber* capacityValue = powerInfo[@kIOPSCurrentCapacityKey];
            NSNumber* maxValue = powerInfo[@kIOPSMaxCapacityKey];
            if (capacityValue!=nil && maxValue!=nil)
                capacityRemaining = [capacityValue doubleValue]/[maxValue doubleValue];
            DebugLogger(@"power source is '%@', battery=%d, capacity=%@, max=%@, remaining=%f%%",
                        powerInfo[@kIOPSPowerSourceStateKey],
                        (int)battery,
                        capacityValue,maxValue,capacityRemaining*100);
            }
        }

    // ...
}

请注意,回调已安装在主运行循环中,因此通知将始终发布在主线程上.

Note that the callback is installed on the main run loop, so the notification will always be posted on the main thread.

这篇关于接收有关笔记本电脑OSX Cocoa中电源线开/关的通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆