Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WifiManager.WifiInfo getSSID & getBSSID not working if targetSdkVersion >= 26

I'm getting correctly those values if I compile with API 27 but target API 25. If I set targetSdkVersion to 27, then, those values are not correctly retrieved.

Targeting SDK 25 or less, values are correct, but targeting 26 or more, I get those values:

SSID gives <unknown ssid>

BBSSID gives 02:00:00:00:00:00

These are my manifest permissions, all are normal permissions and don't require user grant:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

And this is the sample code:

WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
connectionInfo.getSSID();
connectionInfo.getBSSID();

What has changed when targeting SDK 26 or more? what more should we do to get those values?

like image 645
NullPointerException Avatar asked Mar 11 '18 20:03

NullPointerException


2 Answers

Google has changed their policy with WifiManager since you can track user's location tracking wifi location from SDK>=27. Therefore you need to access location permission in order to use getSSID() for your appliaction. In order to use this code follow below.

As @Samuel Eminet answer above, you need either ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION. I used ACCESS_FINE_LOCATION because ACCESS_COARSE_LOCATION request permission for only NETWORK_PROVIDE whereas ACCESS_FINE_LOCATION request permissions for NETWORK_PROVIDE AND GPS_PROVIDER.

Refer here for more information

In your Manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

and where your wifi manager is, add this code to request permissions.

 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED){

        //Permission Not Granted
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
    }



    @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {                                   
        switch (requestCode) {

        case PERMISSION_FINE_LOCATION:
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //permission granted keep going status
                Log.d(TAG, "PERMISSION GRANTED");
            }
            else {
                Log.d(TAG, "PERMISSION DENIED");
            }
    }
}
like image 22
Jay Ryu Avatar answered Nov 10 '22 15:11

Jay Ryu


You need location permission starting with API 27

like image 72
Samuel Eminet Avatar answered Nov 10 '22 16:11

Samuel Eminet