iOS电池的监听

本文介绍了一个简单的iOS应用程序如何获取和显示设备的电池状态及剩余电量。通过启用UIDevice的电池监听功能,可以在应用中实时更新电池信息,并根据不同状态进行显示。

#import "ViewController.h"

#import <UIKit/UIKit.h>

@interface ViewController ()




//@property(nonatomic,readonly) float     batteryLevel NS_AVAILABLE_IOS(3_0);


// 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown它返回的是0.00-1.00之间的浮点值。

@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    //打开电池的监听

    [UIDevice currentDevice].batteryMonitoringEnabled = YES;

    //获取电池的状态

    UIDeviceBatteryState BatteryState = [UIDevice currentDevice].batteryState;

    //获取剩余电量 范围在0.000000  1.000000之间

    CGFloat batterylevel = [UIDevice currentDevice].batteryLevel;

    //battery的状态分为:

    /*

     UIDeviceBatteryStateUnknown,     未知

     UIDeviceBatteryStateUnplugged,   // 未充电

     UIDeviceBatteryStateCharging,     // 正在充电

     UIDeviceBatteryStateFull,             // 满电

     

     */

    if (BatteryState == UIDeviceBatteryStateUnknown) {

        self.dlLabel.text = [NSString stringWithFormat:@"%0.0f%%",batterylevel*100];

        NSLog(@"unknow");

    }else{

        NSLog(@"know");

        //将剩余的电量用label显示。

        self.dlLabel.text = [NSString stringWithFormat:@"%0.0f%%",batterylevel*100];

    }

    

    

    

//    

//    [self getCurrentBatteryLevel];

//    [UIDevice currentDevice].batteryMonitoringEnabled = YES;

//    [[NSNotificationCenter defaultCenter]

//     addObserverForName:UIDeviceBatteryLevelDidChangeNotification

//     object:nil queue:[NSOperationQueue mainQueue]

//     usingBlock:^(NSNotification *notification) {

//         // Level has changed

//         dl=[UIDevice currentDevice].batteryLevel;

//         NSLog(@"电池电量:%.2f", [UIDevice currentDevice].batteryLevel);

//         

//         self.dlLabel.text = [NSString stringWithFormat:@"%f",[UIDevice currentDevice].batteryLevel];

//         

//     }];

    

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}











本文转自 卓行天下  51CTO博客,原文链接:http://blog.51cto.com/9951038/1831784,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值