Search code examples
androidwifiandroid-wifiinternet-connection

How to check if I am connected to a certain wifi network?


I am completely new to developing android apps. I want to have my app (constantly or maybe every few minutes) check in the background whether I am connected to a certain wifi network. If so, it should call a certain class. Unfortunately, there is not much of a code snippet I could provide as of now. Can any one help me to do this?


Solution

  • Just define a method that will determine if the device is currently connected to a specific SSID:

    public boolean isConnectedTo(String ssid, Context context) {
        boolean retVal = false;
        WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifi.getConnectionInfo();
        if (wifiInfo != null) {
            String currentConnectedSSID = wifiInfo.getSSID();
            if (currentConnectedSSID != null && ssid.equals(currentConnectedSSID)) {
                retVal = true;
            }
        }
        return retVal;
    }
    

    Then just use the method like this:

    if (isConnectedTo("SOME_SSID", MainActivity.this)) {
        //Call into other class
    }