Home > Net >  How to check Wi-Fi settings state 'ON' or 'OFF' even if not connected to a WiFi
How to check Wi-Fi settings state 'ON' or 'OFF' even if not connected to a WiFi

Time:04-02

I need to develop a feature that is required checking Wi-Fi settings state 'ON' or 'OFF' even if not connected to a WiFi network on Android! I need to display a pop up!

 public static boolean CheckWifiConnection(Context context) {
    ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
    return conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable();
}

For an example: Think I am in a bus, I have turned on the WiFi. It is not connected to a wifi network, because there is no WiFi router near by. So How can my app knows wifi is on or off.

enter image description here

CodePudding user response:

I think you should to use ConnectivityManager.

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
    @Override
    public void onAvailable(Network network) {
        // network available
    }

    @Override
    public void onLost(Network network) {
        // network unavailable
    }
};

How to check a type of connection

ConnectivityManager

CodePudding user response:

You can use ConnectivityManager to get network status

private boolean isNetworkAvailable() {
            ConnectivityManager connectivityManager
                    = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
  • Related