我编写了以下代码来检查互联网连接
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) {
return false;
} else {
if (activeNetwork.isConnected()) {
return true;
}
}
}
答案 0 :(得分:0)
使用此代码:
public static boolean isInternetconnected(Context ct) {
boolean connected = false;
//get the connectivity manager object to identify the network state.
ConnectivityManager connectivityManager = (ConnectivityManager)ct.getSystemService(Context.CONNECTIVITY_SERVICE);
//Check if the manager object is NULL, this check is required. to prevent crashes in few devices.
if(connectivityManager != null) {
//Check Mobile data or Wifi net is present
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
} else {
connected = false;
}
return connected;
} else {
return false;
}
}