Android 判断手机是否连接网络及连接的网络类型,代码如下:
// 判断手机的网络状态(是否联网)
public static int getNetWorkInfo(Context context) {
//网络状态初始值
int type = -1; //-1(当前网络异常,没有联网)
//通过上下文得到系统服务,参数为网络连接服务,返回网络连接的管理类
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//通过网络管理类的实例得到联网日志的状态,返回联网日志的实例
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//判断联网日志是否为空
if (activeNetworkInfo == null) {
//状态为空当前网络异常,没有联网
return type;
}
//不为空得到使用的网络类型
int type1 = activeNetworkInfo.getType();
switch (type1) {
case ConnectivityManager.TYPE_MOBILE: //网络类型为运营商(移动/联通/电信)
type = 0;
break;
case ConnectivityManager.TYPE_WIFI: //网络类型为WIFI(无线网)
type = 1;
break;
default:
type = -1;
break;
}
//返回网络类型
return type;
}