在AndroidManifest.xml中添加必要权限:
<uses-permission android:name="android.permission.INTERNET" /> <!-仅当需要访问系统ping命令时(需root权限) --> <!-<uses-permission android:name="android.permission.ACCESS_SUPERUSER" /> -->
public class PingUtil { / 执行ping命令并返回结果 @param host 目标主机地址(如"www.baidu.com") @param timeout 超时时间(毫秒) @return 包含状态码和延迟时间的PingResult对象 / public static PingResult pingHost(String host, int timeout) { Process process = null; try { // 构建ping命令(-c 1表示发送1个包,-W指定超时时间) String[] command = {"/system/bin/ping", "-c", "1", "-W", String.valueOf(timeout / 1000), host}; process = Runtime.getRuntime().exec(command); // 读取命令输出 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; StringBuilder output = new StringBuilder(); while ((line = reader.readLine()) != null) { output.append(line).append(" "); } // 解析输出结果 int status = process.waitFor(); if (status == 0) { // 正则匹配延迟时间(单位ms) Pattern pattern = Pattern.compile("time=(\d+) ms"); Matcher matcher = pattern.matcher(output.toString()); int time = matcher.find() ? Integer.parseInt(matcher.group(1)) : -1; return new PingResult(true, time); } else { return new PingResult(false, -1); } } catch (IOException | InterruptedException e) { e.printStackTrace(); return new PingResult(false, -1); } finally { if (process != null) { process.destroy(); } } } public static class PingResult { public boolean success; // 是否ping通 public int latency; // 延迟时间(ms) public PingResult(boolean success, int latency) { this.success = success; this.latency = latency; } } }
public class PingUtilTest { @Test public void testPingSuccess() { PingUtil.PingResult result = PingUtil.pingHost("www.baidu.com", 3000); assertTrue("应ping通百度", result.success); assertTrue("延迟应大于0", result.latency > 0); } @Test public void testPingFailure() { PingUtil.PingResult result = PingUtil.pingHost("192.168.99.999", 2000); assertFalse("不应ping通无效IP", result.success); assertEquals("延迟应为-1", -1, result.latency); } }
问题现象 | 原因分析 | 解决方案 |
---|---|---|
java.io.IOException: Permission denied | 缺少INTERNET权限或未授予ROOT权限 | 检查AndroidManifest权限配置 使用root设备或移除SU相关代码 |
延迟时间始终为-1 | 设备不支持标准ping输出格式 | 改用正则表达式匹配不同设备的输出格式 |
命令执行超时 | 网络环境差或超时时间设置过短 | 增加超时时间参数(如-W 5) |
Q1:如何在不使用ROOT权限的情况下实现ping功能?
A1:安卓4.0+系统自带/system/bin/ping
命令,可直接调用无需ROOT,若部分设备缺失该命令,可尝试使用ip
命令替代方案:ip -f -s address
检测连通性。
Q2:如何优化ping性能并支持多线程检测?
A2:1. 使用线程池管理并发请求 2. 将网络操作移至子线程 3. 复用Process对象减少资源消耗 4. 采用异步回调机制返回结果