1 获取ConnecttiveManager对象
Context context = activity.getApplicationContext();
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
2 获取全部的NetworkInfo:
注:由于getAllNetworkInfo这个方法在SDK版本23中已经被弃用,就用getAllNetworks方法代替,但是由于getAllNetworks方法是在版本21中才添加的,所以首先判断手机的SDK版本信息,如果是21以上的手机就用getAllNetworks方法,反之就只能继续用getAllNetworkInfo方法了
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivityManager.getAllNetworks();
if (networks != null && networks.length > 0) {
int size = networks.length;
for (int i=0; i<size; i++) {
Log.d("TAG", "=====状态====" + connectivityManager.getNetworkInfo(networks[i]).getState());
Log.d("TAG", "=====类型====" + connectivityManager.getNetworkInfo(networks[i]).getTypeName());
if (connectivityManager.getNetworkInfo(networks[i]).getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
} else {
NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
if (networkInfos != null && networkInfos.length > 0) {
int size = networkInfos.length;
for (int i=0; i<size; i++) {
Log.d("TAG", "=====状态====" + networkInfos[i].getState());
Log.d("TAG", "=====类型====" + networkInfos[i].getTypeName());
if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
}