3

I have used the below code for fetching the Wifi name in android. Below is the code that i have used:

WifiManager wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
       WifiInfo info;
       if (wifiManager != null && isWebViewLoaded) {
           info = wifiManager.getConnectionInfo();
           String wifiName = info.getSSID();
}

The code works on other devices (below version 8), however I tried on Nexus 5X (Oreo v-8.1), it gives "Unknown SSID" against info.getSSID().

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Joyson
  • 1,643
  • 5
  • 28
  • 48
  • 1
    you can try something like this https://stackoverflow.com/questions/21391395/get-ssid-when-wifi-is-connected – Vinod Pattanshetti Dec 28 '17 at 08:59
  • 2
    I don't believe this is really a duplicate nor do those other solutions linked above and answered below address this. It appears to be an Android 8 or 8.1 issue. My Pixel 2 running 8.1 is giving me . However, this only happens when I target API 26, API 25 or lower seemed to work fine. – Glaucus Jan 20 '18 at 05:56
  • 5
    Alright, I figured this one out. It appears that in Android 8.1 (maybe 8.0 as well?) if you're targeting API 26+ getSSID() will always return UNLESS your app has the following permission: ACCESS_COARSE_LOCATION. There is a bug logged for this behavior: https://issuetracker.google.com/issues/70795529 . I can't add an answer to this question because it was erroneously marked as a duplicate. It clearly is not. – Glaucus Feb 04 '18 at 21:12
  • Thanks. I don't think it's a bug though. They do the same for bluetooth scanning. It's a horrible way to do it and confuses the user, but it's meant as additional security – behelit Mar 19 '18 at 05:55
  • As @Glaucus said, from Android 8 you have to explicitly request those location permissions via `ActivityCompat.requestPermissions` – AlexAndro Mar 27 '18 at 12:43
  • @AlexAndro Event after requesting permission I am getting unknown ssid! – Gurleen Sethi Apr 08 '18 at 13:47
  • @GurleenSethi you also have to turn on GPS location thing. It seems that from 8.1+ it doesn't matter what SDK you target, you will still get unknown ssid unless you allow all those permissions plus GPS. i.e I'm targeting 25 but on Android P it shows unknown SSID – behelit May 17 '18 at 01:00

1 Answers1

0

Try this code, original answer here

public String getWifiName(Context context) {
   WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (manager.isWifiEnabled()) {
       WifiInfo wifiInfo = manager.getConnectionInfo();
       if (wifiInfo != null) {
          DetailedState state = WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState());
          if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) {
              return wifiInfo.getSSID();
          }
       }
    }
    return null;
}
AwaisMajeed
  • 2,254
  • 2
  • 10
  • 25