Android开发--判断网络是否连接

本文介绍了几种检查设备网络连接状态的方法,包括通过Android系统API获取WiFi和移动数据连接状态,以及使用ping命令验证互联网连通性。此外还提供了一种通过发送HTTP GET请求来判断服务器是否可达的方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

判断网络是否已经连接:

// check all network connect, WIFI or mobile
public static boolean isNetworkAvailable(final Context context) {
    boolean hasWifoCon = false;
    boolean hasMobileCon = false;

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfos = cm.getAllNetworkInfo();
    for (NetworkInfo net : netInfos) {

        String type = net.getTypeName();
        if (type.equalsIgnoreCase("WIFI")) {
            LevelLogUtils.getInstance().i(tag, "get Wifi connection");
            if (net.isConnected()) {
                hasWifoCon = true;
            }
        }

        if (type.equalsIgnoreCase("MOBILE")) {
            LevelLogUtils.getInstance().i(tag, "get Mobile connection");
            if (net.isConnected()) {
                hasMobileCon = true;
            }
        }
    }
    return hasWifoCon || hasMobileCon;

}

利用 ping 判断 Internet 能够 请求成功

// network available cannot ensure Internet is available
public static boolean isNetWorkAvailable(final Context context) {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process pingProcess = runtime.exec("/system/bin/ping -c 1 www.baidu.com");
        int exitCode = pingProcess.waitFor();
        return (exitCode == 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

其他方案 模拟 get 请求

也可以访问网址, 看 get 请求能不能成功

URL url = new URL("http://www.google.com");
 HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
 urlc.setConnectTimeout(3000);
 urlc.connect();
 if (urlc.getResponseCode() == 200) {
     return new Boolean(true);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值