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 ww