【技术篇】Android开发中判断当前网络是否可上网,而不是判断是否连接

在Android开发中,遇到一个bug:手动设置时间后,网络连接正常但静态IP或网络不可上网时,时间获取异常。问题在于`isNetworkAvalible()`方法只能检查网络连接,无法确认网络是否可上网。解决方法是通过ping网关来检测网络实际可达性,虽然ping操作可能稍慢,但能确保判断准确性。
摘要由CSDN通过智能技术生成

问题场景: 

最近开发中遇到一个bug,在设置日期和时间时,手动设置时间,开关机时间正常.使用自动获取网络时间,连接可上网的网络,获取时间也是正常.

但在使用静态IP时或者网络不可上网时,获取的时间就是异常的.

问题分析:

代码如下:

private void setAutoTime() {
    if (isNetworkAvalible(getActivity())) {
        Log.d("setRTCTime", "===setAutoTime===isNetworkAvalible====");
        final Calendar calendar = Calendar.getInstance();
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL urlTime = null;//取得资源对象
                try {
                    urlTime = new URL("https://www.baidu.com");
                    URLConnection uc = urlTime.openConnection();//生成连接对象
                    uc.setConnectTimeout(3000);
                    uc.connect(); //发出连接
                    long autoTime = uc.getDate(); //取得网站日期时间
                    Date date = new Date(autoTime); //转换为标准时间对象
                    date.getDate();
                    Log.d("setRTCTime", "===setAutoTime===autoTime====" + autoTime);
                    if (autoTime == 0) {
                        return;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

public boolean isNetworkAvalible(Context context) {
// 获得网络状态管理器
    ConnectivityManager connectivityManager = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager == null) {
        return false;
    } else {
        // 建立网络数组
        NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();
        if (net_info != null) {
            for (int i = 0; i < net_info.length; i++) {
          
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Love~妍芯~燕~Love

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值