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

前端 未结 18 1440
轮回少年
轮回少年 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条回答
  •  天命终不由人
    2020-12-04 16:14

    This will tell if you're connected to a network:

    boolean connected = false;
    ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            //we are connected to a network
            connected = true;
        }
        else
            connected = false;
    

    Warning: If you are connected to a WiFi network that doesn't include internet access or requires browser-based authentication, connected will still be true.

    You will need this permission in your manifest:

    
    

提交回复
热议问题