获取 ios 系统网络状况、电量

来源:互联网 发布:知乎 加拿大袜子精 编辑:程序博客网 时间:2024/04/30 09:34
本篇博客出自阿修罗道,转载请注明出处:http://blog.csdn.net/fansongy/article/details/8927734

cocos2d-x中并没有关于获取一些系统底层信息的方法。由于跨平台编译的原因,需要根据平台来自己写。

通常需要显示是网络连接状态和电池的电量这两个。

[cpp] view plaincopyprint?
  1. #import "Foundation/Foundation.h"  
  2. #import "UIKit/UIKit.h"  
  3.   
  4. typedef enum  
  5. {  
  6.     // Apple NetworkStatus Compatible Names.  
  7.     NoNetWork    = 0,  
  8.     ConnWiFi     = 2,  
  9.     Conn3G       = 1  
  10. } NetState;  
  11.   
  12.   
  13. // 获取电池电量,范围0到1.0。-1表示电量未知。  
  14. float getBatteryLeve();  
  15.   
  16. // 检测WIFI是否可用  
  17. bool isWIFIEnabled();  
  18.   
  19.   
  20. // 检测3G网络是否可用  
  21. bool is3GEnabled();  
  22.   
  23. //取得网络连接状况  
  24. NetState getNetState();  

实现是用.mm来实现,就是调用一些ios现成的接口。

[cpp] view plaincopyprint?
  1. #include "SystemInfo.h"  
  2. #import "Reachability.h"  
  3.   
  4. NSString* testPage = @"www.baidu.com";  
  5.   
  6. float getBatteryLeve()  
  7. {  
  8.     [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];  
  9.     return [[UIDevice currentDevice] batteryLevel];  
  10. }  
  11.   
  12. // 检测WIFI是否可用  
  13. bool isWIFIEnabled()  
  14. {  
  15.     return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);  
  16. }  
  17.   
  18. // 检测3G网络是否可用  
  19. bool is3GEnabled()  
  20. {  
  21.     return [[Reachability reachabilityForInternetConnection] isReachableViaWWAN];  
  22. }  
  23.   
  24.   
  25. NetState getNetState()  
  26. {  
  27.       
  28.     Reachability *r = [Reachability reachabilityWithHostname:testPage];  
  29.     switch ([r currentReachabilityStatus]) {  
  30.         case NotReachable:  
  31.             // 没有网络连接  
  32.             return NoNetWork;  
  33.             break;  
  34.         case ReachableViaWWAN:  
  35.             // 使用3G网络  
  36.             return Conn3G;  
  37.             break;  
  38.         case ReachableViaWiFi:  
  39.             // 使用WiFi网络  
  40.             return ConnWiFi;  
  41.             break;  
  42.     }  
  43.        
  44. }  

    其中Reachability类是官方给提供的一个测试网络的类。使用时引入Reachability.h 和.m就可以,另外还要在Frameworks中加入SystemConfiguration.framework。一些使用可以百度,我下面的源码中也能找到相应的项目。

 

    源码:http://download.csdn.net/detail/fansongy/5377491

0 0