Android 判断网络
函数用于判断网络是否可用
/*
*@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;
}
所以呢,你找到办法没有啊?求教。
博主提供的两种方法貌似都不行,只能判断是否连接了网络线路,不能判断是否能连接外网(如www.baidu.com)
如果手机连接是一个假网络,比如手机连接wifi, 这个wifi只是有几条线路是通的,真正连接到外网的线路并不连接,
按照此代码将提示连网成功, 实际上并不能打开外网......
** :oops: **