由于工作需求,这几天一直在研究IOS
如何获取到的电量及网络类型
做之前我们首先要找到IOKit.tbd这个动态库及两个API头文件(IOPowerSources.h和IOPSKeys.h)
在Xcode ->显示包含内容->Contents->Developer->Platforms->iPhoneOS.platform->Developer->SDKs->iPhoneOS.sdk->System->Library->Frameworks
下找到IOKit.framework 并找到IOKit.tbd这个库及IOPowerSources.h和IOPSKeys.h
Unity 代码:
[DllImport("__Internal")]
static extern int IOS_GetPhoneElectricity();
[DllImport("__Internal")]
static extern string IOS_GetNetworkType();
IOS代码:
#if defined(__cplusplus)
extern "C"{
#endif
int IOS_GetPhoneElectricity()
{
NSLog(@"IOS_GetPhoneElectricity Start=UnityToIOS batteryLevel");
return (int)[UnityToIOS batteryLevel];
}
char* IOS_GetNetworkType ()
{
NSString *tmp =[UnityToIOS networkingStatesFromStatebar];
const char* str =[tmp UTF8String];
char* res = (char*)malloc([tmp length]+1);
strcpy(res, str);
return res;
}
#if defined(__cplusplus)
}
#endif
+ (NSString *)networkingStatesFromStatebar
{
// 状态栏是由当前app控制的,首先获取当前app
UIApplication *app = [UIApplication sharedApplication];
NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
int type = 0;
for (id child in children) {
if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
}
}
NSString *stateString = @"WIFI";
switch (type) {
case 0:
stateString = @"None"; // 没有网络
break;
case 1:
stateString = @"2G";
break;
case 2:
stateString = @"3G";
break;
case 3:
stateString = @"4G";
break;
case 4:
stateString = @"LTE"; // 比4G更快的蜂窝网
break;
case 5:
stateString = @"WIFI";
break;
}
return stateString;
}
+ (double) batteryLevel
{
CFTypeRef blob = IOPSCopyPowerSourcesInfo();
CFArrayRef sources = IOPSCopyPowerSourcesList(blob);
CFDictionaryRef pSource = NULL;
const void *psValue;
long numOfSources = CFArrayGetCount(sources);
if (numOfSources == 0) {
NSLog(@"Error in CFArrayGetCount");
return -1.0f;
}
for (int i = 0 ; i < numOfSources ; i++)
{
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;
}
最后感谢那些为程序作出贡献的博客作者,因为有了他们才能让我们程序学习更快,更好