我要检查是否存在 Activity 的互联网连接。为此,我found out可以使用InetAddress类中的isReachable()方法实现。不幸的是(正如JavaDoc所建议以及这篇verifies所建议的那样),这仅适用于根特权,这无法解决我的问题。

当我运行以下代码时,isReachable始终为false:

InetAddress address = InetAddress.getByName("173.194.35.3"); //e.g. google
boolean isReachable = address.isReachable(2000); //ms

因此,我正在寻找一个很好的替代方法来检查是否存在有效的Internet连接,而无需root特权。

谢谢!

最佳答案

它可能很旧,但是我遇到了同样的问题,在阅读了这些答案之后,我发现了这个了不起的库icmp 4j并解决了所有问题。您可以下载源代码here并在项目中使用类似这样的内容

// request
final IcmpPingRequest request = IcmpPingUtil.createIcmpPingRequest ();
request.setHost ("192.168.0.101");

// repeat a few times
for (int count = 1; count <= 4; count ++) {

// delegate
final IcmpPingResponse response = IcmpPingUtil.executePingRequest (request);

// log
final String formattedResponse = IcmpPingUtil.formatResponse (response);
System.out.println (formattedResponse);

// rest
Thread.sleep (1000);
}

08-07 11:10