How to check currently internet connection is available or not in android

前端 未结 18 1454
轮回少年
轮回少年 2020-12-04 15:40

I want to execute my application offline also, so I need to check if currently an internet connection is available or not. Can anybody tell me how to check if internet is av

18条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 16:10

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        } else {
            return false;
        }
    }
    

    Google recommends this code block for checking internet connection. Because the device may have not internet connection even if it is connected to WiFi.

提交回复
热议问题