Android version 9 (Pie) changes require Location to be enabled (by the user), or the call to getConnectioInfo() will fail, even if your app has correct permissions.
This is documented in the Android 9 changes (excerpt below):
Restricted access to Wi-Fi location and connection information
In Android 9, the permission requirements for an app to perform Wi-Fi scans are more strict than in previous versions. For details, see Wi-Fi scanning restrictions.
Similar restrictions also apply to the getConnectionInfo() method, which returns a WifiInfo object describing the current Wi-Fi connection. You can only use this object's methods to retrieve SSID and BSSID values if the calling app has the following permissions:
- ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION
- ACCESS_WIFI_STATE
Retrieving the SSID or BSSID also requires location services to be enabled on the device (under Settings > Location).
In my case, I call the function below (only if running on Android 9+) to detect if location is enabled, prior to attempting to read the WIFI SSID.
public static boolean isLocnEnabled(Context context) {
List locnProviders = null;
try {
LocationManager lm =(LocationManager) context.getApplicationContext().getSystemService(Activity.LOCATION_SERVICE);
locnProviders = lm.getProviders(true);
return (locnProviders.size() != 0);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (BuildConfig.DEBUG) {
if ((locnProviders == null) || (locnProviders.isEmpty()))
Log.d(TAG, "Location services disabled");
else
Log.d(TAG, "locnProviders: " + locnProviders.toString());
}
}
return(false);
}
If location is not enabled, I pop up a dialog that says it's required, and allows the user to jump to the location settings page (see code below):
context.startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));