public class NetworkState {
public boolean isconnect(Context context) {
//检测API是不是小于21,因为到了API21之后getNetworkInfo(int networkType)方法被弃用
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取ConnectivityManager对象对应的NetworkInfo对象
//获取WIFI连接的信息
NetworkInfo wifiNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//获取移动数据连接的信息
NetworkInfo dataNetworkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
Toast.makeText(context, "WIFI已连接,移动数据已连接", Toast.LENGTH_SHORT).show();
return true;
} else if (wifiNetworkInfo.isConnected() && !dataNetworkInfo.isConnected()) {
Toast.makeText(context, "WIFI已连接", Toast.LENGTH_SHORT).show();
return true;
} else if (!wifiNetworkInfo.isConnected() && dataNetworkInfo.isConnected()) {
Toast.makeText(context, "移动数据已连接", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(context, "WIFI已断开,移动数据已断开", Toast.LENGTH_SHORT).show();
return false;
}
}else {
//获得ConnectivityManager对象
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取所有网络连接的信息
Network[] networks = connMgr.getAllNetworks();
//用于存放网络连接信息
StringBuilder sb = new StringBuilder();
List list = new ArrayList<>();
//通过循环将网络信息逐个取出来
for (int i=0; i < networks.length; i++){
//获取ConnectivityManager对象对应的NetworkInfo对象
NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
sb.append((networkInfo.getType() == ConnectivityManager.TYPE_MOBILE ? "移动数据" : "Wifi" ) + (networkInfo.isConnected() ? " 已连接": " 已断开"));
list.add(networkInfo.isConnected());
}
}
Toast.makeText(context, sb.toString(),Toast.LENGTH_SHORT).show();
//没有网络返回false
if (!list.contains(true)) {
return false;
}
return true;
}
}
}
网友评论