如何获得电池状态?

Rav*_*ash 16 iphone cocoa-touch

如何在iPhone上获取电池状态?

Par*_*kor 24

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batLeft = [myDevice batteryLevel];
int i=[myDevice batteryState];

int batinfo=(batLeft*100);

NSLog(@"Battry Level is :%d and Battery Status is :%d",batinfo,i);

switch (i)
{
    case UIDeviceBatteryStateUnplugged:
    {
        [BCStatus setText:NSLocalizedString(@"UnpluggedKey", @"")];
        break;
    }
    case UIDeviceBatteryStateCharging:
    {
        [BCStatus setText:NSLocalizedString(@"ChargingKey", @"")];
        break;
    }
    case UIDeviceBatteryStateFull:
    {
        [BCStatus setText:NSLocalizedString(@"FullKey", @"")];
        break;
    }
    default:
    {
        [BCStatus setText:NSLocalizedString(@"UnknownKey", @"")];
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

BCStatus是uilabel.

  • 值得注意的是,如果您的应用程序在后台执行,则不会发送相关通知"UIDeviceBatteryLevelDidChangeNotification"和"UIDeviceBatteryStateDidChangeNotification" (4认同)