iOS 獲取手機(jī)電量 電量變化通知


#pragma mark - 電池電量獲取及監(jiān)控
-(void)checkAndMonitorBatteryLevel{
    
    //拿到當(dāng)前設(shè)備
    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ā)生改變時調(diào)用
    UIDevice *myDevice = [UIDevice currentDevice];
    [myDevice setBatteryMonitoringEnabled:YES];
    float batteryLevel = [myDevice batteryLevel];
    NSLog(@"電池剩余比例:%@", [NSString stringWithFormat:@"%f",batteryLevel*100]);
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容