Categories
Allgemein

Check permissions before your Android app uses BLE

If you want to implement an android app that use BLE,  the app must get the ACCESS_COARSE_LOCATION permissions. Android will then automatically ask the user if he/she agrees when using a bluetooth function for the first time.(for example at startScan). But if the app has no permissions to use the location, your bluetooth call will fail. Therefore, an early check is better to avoid this problem. 

My approach looks like this:

1) Add to your AndroidManifest.xml:

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

If you only use BLE it es sufficient to request the coarse location permission (location without GPS). If you need a GPS position for your app, you can replace ACCESS_COARSE_LOCATION with ACCESS_FINE_LOCATION. You don’t need both.

2) Then add the permission check to place before the first called bluetooth method.  For example directly after starting the app.

private boolean hasLocationPermission() {

  if (ContextCompat.checkSelfPermission(
    context, 
    Manifest.permission.ACCESS_COARSE_LOCATION
    ) != PackageManager.PERMISSION_GRANTED) {

    ActivityCompat.requestPermissions(
      getCurrentActivity(),
      new String[] {
        Manifest.permission.ACCESS_COARSE_LOCATION
      },
      REQUEST_COARSE_LOCATION_PERMISSIONS);
    return false;
  } else {
    doWhatEverYouWillDoWithBluetooth();
    return true;
  }
}

3) Finally, the callback must be implemented in your activity class to react to the user’s decision

public void onRequestPermissionsResult(
  int requestCode, 
  String permissions[], 
  int[] grantResults) {

  if (requestCode == REQUEST_COARSE_LOCATION_PERMISSIONS) {
    if (grantResults.length > 0 && grantResults[0] ==  
      PackageManager.PERMISSION_GRANTED) {
      
      doWhatEverYouWillDoWithBluetooth();
    } else {
      doWhatEverYouWillDoWithoutBluetooth();
    }
  }
}

That’s it.

Leave a Reply

Your email address will not be published. Required fields are marked *