iOS
#pragma mark - 電池電量獲取及監(jiān)控
-(void)checkAndMonitorBatteryLevel{
//拿到當前設備
UIDevice * device = [UIDevice currentDevice];
//是否允許監(jiān)測電池
//要想獲取電池電量信息和監(jiān)控電池電量 必須允許
device.batteryMonitoringEnabled = true;
//1腌零、check
/*
獲取電池電量
0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown
*/
float level = device.batteryLevel;
NSLog(@"level = %lf",level);
//2梯找、monitor
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeBatteryLevel:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
}
- (void)didChangeBatteryLevel:(id)sender{
//電池電量發(fā)生改變時調用
UIDevice *myDevice = [UIDevice currentDevice];
[myDevice setBatteryMonitoringEnabled:YES];
float batteryLevel = [myDevice batteryLevel];
NSLog(@"電池剩余比例:%@", [NSString stringWithFormat:@"%f",batteryLevel*100]);
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeBatteryLevel:) name:@"UIDeviceBatteryLevelDidChangeNotification" object:device];
Android:
private BroadcastReceiver myBatteryReceiver =
new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
int bLevel = arg1.getIntExtra("level", 0);// the battery level in integer
//添加自定義回調
}
};