ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
//判断网络连接类型,此处为wifi
NetworkInfo networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//此处判断网络是否连接(注:此处只能判断网络是否连接,不能判断网络是否可用)
if (networkInfo != null)
return networkInfo.getState() == NetworkInfo.State.CONNECTED;
判断网络是否可用常使用以下三种方法:
1.根据DNS
try {
Socket s=null;
if (s == null) {
s = new Socket();
}
InetAddress host = InetAddress.getByName("8.8.8.8");//国内使用114.114.114.114,如果全球通用google:8.8.8.8
s.connect(new InetSocketAddress(host, 53), 5000);//google:53
s.close();
} catch (IOException e) {
}
2.根据ping命令
try {
Process process = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 100 www.baidu.com");
int status = process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
//如果status==0则表示网络可用,其中参数-c 1是指ping的次数为1次,-w是指超时时间单位为s
3.直接用http连接网络
URL url;
try {
url = new URL("https://www.baidu.com");
InputStream stream = url.openStream();
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
作者:KieSnow