Android里面有ConnectivityManager可以判断当前的网络状态。
判断是否有可用的网络
如果你只是想判断当前是不是有可用的网络(不在乎wifi或者流量的话),可以使用如下代码
/**
* 是否已经连接网络(外网不一定通)
* @return
*/
public boolean isNetConnected() {
if (connectivityManager != null){
Log.d(LOGLABEL, "connectivitymanager is not null");
//获取代表联网对象的NetworkInfo对象
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
Log.d(LOGLABEL , "activityNetworkInfo is not null and isconnected");
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
//获取当前的网络连接是否可用
Log.d(LOGLABEL ,"is mobile or wifi");
return true;
}
return false;
}
return false;
}
getActiveNetworkInfo()
获取当前正连接的网络信息。如果没有任何网络连接的话,会返回null。
判断某wifi是否已经连接
WifiManager是专门管理与wifi有关的操作的。
如果你想判断某个wifi是否已经连接,有以下几个步骤可以判断:
1.判断该SSID是否在手机的wifi配置(WifiConfiguration)中
/**
* 传入某个SSID,判断该网络的配置是不是在配置列表中
* @param ssid
* @return
*/
public WifiConfiguration isSSIDExistInConfiguration(String ssid){
WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> configureList = manager.getConfiguredNetworks();
if (configureList != null){
for (WifiConfiguration configuration : configureList){
if(configuration.SSID.equals("\""+ssid+"\"")){ //直接判断equals(ssid)肯定是不存在的,因为“XXX_WIFI”才是配置中的SSID,它外面包了双引号
return configuration;
}
}
}
return null;
}
2.当然,在配置列表中也不一定代表一定连接上了。但不在配置列表中肯定是没连接上的。此时configuration里面有这个SSID的status,可以判断它。
-1没找到该网络,0已经连接,1不可连接,2可以连接.
判断外网是否可通
有时候仅仅判断是否有可用的网络还不够,还想要判断外网是否可通。
网络上的解决办法是ping
大家基本上给出的是以下代码【但是我每次测试的结果都是外网不通,所以放弃了以下代码】
try {
String ip = "www.baidu.com";
Process process = Runtime.getRuntime().exec("/system/bin/ping -c 3" + ip);
InputStream input = process.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d(LOGLABEL, "----ping----result content=" + stringBuffer);
//ping的状态
int status = process.waitFor();
if (0 == status) {
Log.d(LOGLABEL,"process status = 0");
return true;
} else {
Log.d(LOGLABEL, "process status != 0");
return false;
}
}catch (IOException e) {
Log.d(LOGLABEL, "IOException=");
e.printStackTrace();
}catch (InterruptedException e){
Log.d(LOGLABEL, "InterruptedException");
e.printStackTrace();
}
在网上找了一个库,它可以用来判断外网是否可通,NetStatusManager
一般是NetStatusManager.getInstance().refreshStatus();
去刷新网络状态,我会在3秒之后去NetStatusManager.getInstance().getNetStatus()
获取外网判断结果
这个库的网络状态有WEAK(1, "weak"), GOOD(0, "good"), BREAK(2, "break"), UNKNOW(-1, "unknown"), WAIT(3, "wait");
。至今还没遇到过WEAK的情况。
如果refreshStatus之后马上去getNetStatus,会得到WAIT,或者是上一次的网络状态。所以过几秒再去getNetStatus比较好。