Android 判断是否有外网连接
2021-07-28 本文已影响0人
cain07
app在很多时候需要判断是否能够上外网,并将结果反馈给用户。想到这里很多同学估计会想到判断网络通道是不是打开:
public synchronized boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
上面这段代码只能判断出数据通道是否打开,如果3G/4G流量或者WiFi无法使用,那么这个判断将不再适用。
下面,推荐几种判断网络是否真正可用的方案:
方案一、使用Android自带的api去ping IP地址:
public void pingNet() {
try {
if (InetAddress.getByName("120.25.236.134").isReachable(3000)) {
Log.d("morse", "pingNet onSuccess");
} else {
Log.d("morse", "pingNet onFailure");
}
} catch (Throwable e) {
Log.d("morse", "pingNet onFailure");
}
}
方案二、使用Android自带的api去解析域名:
public void analysisNet() {
// 这种方式如果ping不通 会阻塞一分钟左右
// 也是要放在另一个线程里面ping
try {
InetAddress addr = InetAddress.getByName("www.baidu.com");
if (!addr.isLoopbackAddress() && addr instanceof Inet4Address) {
Log.d("morse", "analysisNet onSuccess ");
} else {
Log.d("morse", "analysisNet onFailure 0");
}
} catch (Throwable e) {
Log.d("morse", "analysisNet onFailure 1 " + e);
}
}
方案三、使用adt命令去ping IP:
public void ping() {
String result = null;
try {
String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
final int status = p.waitFor();
if (status == 0) {
Log.d("morse", "ping onSuccess");
} else {
Log.d("morse", "ping onFailure");
}
} catch (IOException e) {
Log.d("morse", "ping onFailure");
} catch (InterruptedException e) {
Log.d("morse", "ping onFailure");
} finally {
}
}
方案四、使用socket连接:
private boolean isConnect(String ip) {
Socket socket = null;
try {
socket = new Socket(ip, 80);
socket.setKeepAlive(true);
socket.setSoTimeout(10);
Log.d("morse", socket.isConnected() ? "true" : "false");
if (socket.isConnected()) {
socket.sendUrgentData(0xFF);
Log.d("morse", "连接成功");
if (0 != count) {
count = 0;
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
注意:使用这种方式一定要发送心跳包,不然检测状态不会改变。
我采用的 第二张方式 可以 使用。