首页 > 代码库 > 判断网络是否连接

判断网络是否连接

ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

if (activeNetInfo.isConnected()) {
Toast.makeText(context, "WIFI网络连接成功", Toast.LENGTH_SHORT).show();
}
if (mobNetInfo.isConnected()) {
Toast.makeText(context, "手机网络连接成功", Toast.LENGTH_SHORT).show();
}
if(!activeNetInfo.isConnected() && !mobNetInfo.isConnected()) {
Toast.makeText(context, "网络断开连接", Toast.LENGTH_SHORT).show();
}

 

NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();

if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(context, "network is available",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "network is unavailable",
Toast.LENGTH_SHORT).show();
}

NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();//getActivityNetwordInfo是可用网络,不一定是连接的

判断网络是否连接