函数用于判断网络是否可用
/*
*@return boolean return true if the application can access the internet
*/
private boolean haveInternet(){
NetworkInfo info=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();
if(info==null || !info.isConnected()){
return false;
}
if(info.isRoaming()){
//here is the roaming option you can change it if you want to disable internet while roaming, just return false
return true;
}
return true;
}
另一种方法
public boolean isNetworkAvailable() {
Context context = getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
boitealerte(this.getString(R.string.alert),"getSystemService rend null");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
本文提供了两种检查设备网络连接状态的方法。第一种方法通过获取当前活动网络信息并判断是否连接互联网来实现;第二种方法则通过遍历所有网络信息,并检查它们的状态来确定是否有可用的网络连接。
2019

被折叠的 条评论
为什么被折叠?



