原文地址:http://blog.csdn.net/xiaot01/article/details/45893299
备注:ios中主要用到ReachabilityIOSMac.m中的方法,android中主要用到ConnectivityManager
----------1.ios中网络相关函数(主要看实现部分,方法名是lua-quick3.3中的CCNetWork.h中带的):
bool Network::isLocalWiFiAvailable(void)
{
return [[ReachabilityIOSMac reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable;
}
bool Network::isInternetConnectionAvailable(void)
{
return [[ReachabilityIOSMac reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable;
}
bool Network::isHostNameReachable(const char* hostName)
{
NSString *hostName_ = [NSString stringWithUTF8String:hostName];
return [[ReachabilityIOSMac reachabilityWithHostname:hostName_] currentReachabilityStatus] != NotReachable;
}
int Network::getInternetConnectionStatus(void)
{
NetworkStatus status = [[ReachabilityIOSMac reachabilityForInternetConnection] currentReachabilityStatus];
if (status == ReachableViaWiFi) return kCCNetworkStatusReachableViaWiFi;
if (status == ReachableViaWWAN) return kCCNetworkStatusReachableViaWWAN;
return kCCNetworkStatusNotReachable;
}
--------------2.具体实现:
对于此类需要访问设备的问题,触控没有给出具体的方法。下面是我的简单实现,欢迎批评、指正
既然是跨平台,那就要分别解决了,先是Android的
Android:思路就是使用JNI调用Java的静态函数并返回到C++中。具体的请看代码:
C++函数:
void NetworkHelper::setNetType(){
#if CC_TARGET_PLATFORM== CC_PLATFORM_WIN32
_netType = false;
#elif CC_TARGET_PLATFORM== CC_PLATFORM_ANDROID
bool ret = false;
JniMethodInfo info;
bool bHave = JniHelper::getStaticMethodInfo(info, "org/cocos2dx/lib/Cocos2dxActivity", "getNetType", "()Z");
if (bHave){
ret = info.env->CallStaticBooleanMethod(info.classID, info.methodID);
info.env->DeleteLocalRef(info.classID);
}
_netType = ret;
#endif
}
Java的静态函数:
public static boolean getNetType(){
Log.v("df","join");
ConnectivityManager connectivityManager = (ConnectivityManager)sContext.getSystemService(sContext.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo == null || !networkInfo.isAvailable())
{
//当前无可用网络
return false;
}
else
{
//当前有可用网络
return true;
}
}
iOS:思路就是使用混编,调用ObjectC的函数,使用Appel提供的Reachability类来实现功能。具体的请看代码:
void NetworkHelper::setNetType(){
bool _netType;
Reachability *reach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [reach currentReachabilityStatus];
if (netStatus == NotReachable){
_netType = false;
}
else{
_netType = true;
}
}