connectivity-samples
connectivity-samples copied to clipboard
Scanning needs user request for location permission
Scan results in "java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results". Running on Marshmallow.
I added the location permission to the sample code and it work, dont know why it needs location thought, maybe for beacon?
Apparently for SDK > 23 you need to ask the user for those permissions. If you set it to SDK < 22 you won't need to prompt the user for permissions.
The target SDK is set to 24 so it won't work unless you put a prompt in.
I set the target SDK to 22, change the dependencies to v22 and it shows the devices. Success!
http://stackoverflow.com/questions/33149814/prompting-for-location-permission-when-not-monitoring-in-background
For Android N: Add the following permissions,
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
and go to Settings / Apps / BluetoothLeGatt / Permissions and enable Location.
Alternatively, insert this check in OnCreate method for main activity:
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); if (permissionCheck != PackageManager.PERMISSION_GRANTED){ if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){ Toast.makeText(this, "The permission to get BLE location data is required", Toast.LENGTH_SHORT).show(); }else{ requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1); } }else{ Toast.makeText(this, "Location permissions already granted", Toast.LENGTH_SHORT).show(); }
I just needs to clear one doubt, that why we need to turn the device location ON while scanning the beacons?
@Dharmesh-Kudos Thanks for the idea turning ON device location. Now my scan works.
You do not need both permissions.
If you need the users exact location use this:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
you don't need the other permission if you have this one, but this permission is more resource intensive and will cost the user more data, also way less privacy.
Use:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
If you don't need the location of the user updating every couple of seconds and want to keep the user a little more private.
Both permissions will grant you the permission to scan BLE devices.
On an Android 10 (Pixel 4), onScanResult callback is never executed with ACCESS_COARSE_LOCATION
permission. It starts working only after obtaining ACCESS_FINE_LOCATION
.