iOS 개발의runtime 정확한 배터리 확보
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter]
addObserverForName:UIDeviceBatteryLevelDidChangeNotification
object:nil queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *notification) {
// Level has changed
NSLog(@"Battery Level Change");
NSLog(@" :%.2f", [UIDevice currentDevice].batteryLevel);
}];
@property(nonatomic,readonly) float batteryLevel NS_AVAILABLE_IOS(3_0);
// 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown 0.00-1.00 。
그러나 테스트를 통해 iOS7에서는 0.05 단위이지만 iOS9에서 테스트를 하면 0.01 단위이고 0.01 단위이지만 테스트를 여러 번 해도 1% 정도의 편차가 나타난다.즉, 이 방법은 결함이 존재하는데, 적어도 그것은 정확하지 않다는 것이다.
방법2: Mac에서 IOKit를 찾습니다.framework, IOKit.framework의 IOPowerSources.h 및 IOPSKeys.h를 iOS 프로젝트로 복사합니다.또한 IOKit도 당신의 프로젝트에 도입해야 합니다. 이 방법도 편차가 생겨서 정확하지 않습니다.DEMO 주소:https://github.com/colin1994/batteryLevelTest.git
/**
* Calculating the remaining energy
*
* @return Current batterylevel
*/
-(double)getCurrentBatteryLevel
{
//Returns a blob of Power Source information in an opaque CFTypeRef.
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
//Returns a CFArray of Power Source handles, each of type CFTypeRef.
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
CFDictionaryRef pSource = NULL;
const void *psValue;
//Returns the number of values currently in an array.
int numOfSources = CFArrayGetCount(sources);
//Error in CFArrayGetCount
if (numOfSources == 0)
{
NSLog(@"Error in CFArrayGetCount");
return -1.0f;
}
//Calculating the remaining energy
for (int i = 0 ; i < numOfSources ; i++)
{
//Returns a CFDictionary with readable information about the specific power source.
pSource = IOPSGetPowerSourceDescription(blob, CFArrayGetValueAtIndex(sources, i));
if (!pSource)
{
NSLog(@"Error in IOPSGetPowerSourceDescription");
return -1.0f;
}
psValue = (CFStringRef)CFDictionaryGetValue(pSource, CFSTR(kIOPSNameKey));
int curCapacity = 0;
int maxCapacity = 0;
double percent;
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSCurrentCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
psValue = CFDictionaryGetValue(pSource, CFSTR(kIOPSMaxCapacityKey));
CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);
percent = ((double)curCapacity/(double)maxCapacity * 100.0f);
return percent;
}
return -1.0f;
}
방법3:runtime를 통해 StatusBar의 배터리 전량 컨트롤 클래스의 개인 변수의 값을 얻을 수 있으며, 이 방법은 iOS6 이상의 배터리 전량을 정확하게 얻을 수 있다.
MRC:
- (int)getCurrentBatteryLevel
{
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive||[UIApplication sharedApplication].applicationState==UIApplicationStateInactive) {
void *result = nil;
object_getInstanceVariable([UIApplication sharedApplication], "_statusBar", &result);
id status = result;
for (id aview in [status subviews]) {
for (id bview in [aview subviews]) {
int batteryLevel = 0;
if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame&&[[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0)
{
object_getInstanceVariable(bview, "_capacity", &result);
batteryLevel = (int)result;
NSLog(@" :%d",batteryLevel);
if (batteryLevel > 0 && batteryLevel <= 100) {
return batteryLevel;
} else {
return 0;
}
}
}
}
return 0;
}
ARC:
- (int)getCurrentBatteryLevel
{
UIApplication *app = [UIApplication sharedApplication];
if (app.applicationState == UIApplicationStateActive||app.applicationState==UIApplicationStateInactive) {
Ivar ivar= class_getInstanceVariable([app class],"_statusBar");
id status = object_getIvar(app, ivar);
for (id aview in [status subviews]) {
int batteryLevel = 0;
for (id bview in [aview subviews]) {
if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame&&[[[UIDevice currentDevice] systemVersion] floatValue] >=6.0)
{
Ivar ivar= class_getInstanceVariable([bview class],"_capacity");
if(ivar)
{
batteryLevel = ((int (*)(id, Ivar))object_getIvar)(bview, ivar);
//
/*ptrdiff_t offset = ivar_getOffset(ivar);
unsigned char *stuffBytes = (unsigned char *)(__bridge void *)bview;
batteryLevel = * ((int *)(stuffBytes + offset));*/
NSLog(@" :%d",batteryLevel);
if (batteryLevel > 0 && batteryLevel <= 100) {
return batteryLevel;
} else {
return 0;
}
}
}
}
}
}
return 0;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.