NetworInfo.isAvailable和NetworkInfo.isConnected只表明网络连接是否已连上,不能表明连接是否可以访问互联网
要检查设备是否在线,有以下方法:
第一种:
@TargetApi(Build.VERSION_CODES.M)
public static boolean isNetworkOnline1(Context context) {
boolean isOnline = false;
try {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkCapabilities capabilities = manager.getNetworkCapabilities(manager.getActiveNetwork()); // need ACCESS_NETWORK_STATE permission
isOnline = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
} catch (Exception e) {
e.printStackTrace();
}
return isOnline;
}
优点: 1.可以在UI线程上运行;2.快速准确。
缺点:需要 API >= 23 和兼容性问题。
第二种:
public static boolean isNetworkOnline2() {
boolean isOnline = false;
try {
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("ping -c 1 8.8.8.8");
int waitFor = p.waitFor();
isOnline = waitFor == 0; // only when the waitFor value is zero, the network is online indeed
// BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
// String str;
// while ((str = br.readLine()) != null) {
// System.out.println(str); // you can get the ping detail info from Process.getInputStream()
// }
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return isOnline;
}
优点: 1.可以在UI线程上运行;2.可以多次ping,统计min/avg/max延迟时间和丢包率。
缺点:有些手机不行如三星。
第三种
public static boolean isNetworkOnline3() {
boolean isOnline = false;
try {
URL url = new URL("http://www.google.com"); // or your server address
// URL url = new URL("http://www.baidu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.setConnectTimeout(3000);
isOnline = conn.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return isOnline;
}
优点:可以在所有设备和 API 上使用。
缺点: *** 作耗时,不能在UI线程上运行。
第四种
public static boolean isNetworkOnline4() {
boolean isOnline = false;
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("8.8.8.8", 53), 3000);
// socket.connect(new InetSocketAddress("114.114.114.114", 53), 3000);
isOnline = true;
} catch (IOException e) {
e.printStackTrace();
}
return isOnline;
}
优点:1.可以在所有设备和API上使用;2.相对快速准确。
缺点: *** 作耗时,不能在UI线程上运行。
本人用的是第四种:
class InternetCheck extends AsyncTask {
private Consumer mConsumer;
public interface Consumer {
void accept(Boolean internet);
}
public InternetCheck(Consumer consumer) {
mConsumer = consumer;
execute();
}
@Override
protected Boolean doInBackground(Void... voids) {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
sock.close();
return true;
} catch (IOException e) {
return false;
}
}
@Override
protected void onPostExecute(Boolean internet) {
mConsumer.accept(internet);
}
}
new InternetCheck(new InternetCheck.Consumer() {
@Override
public void accept(Boolean internet) {
if (internet){
//
}else{
//
}
}
});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)