Requesting permissions in Android with a Target SDK Version >= 23

Various Android permissions (classed as “dangerous”), within applications targeting Android SDK >= 23 now require “requesting”.

So for example, on older Android versions we simply set the permissions, such as those for accessing Bluetooth, within the AndroidManifest.xml (or via the editor within Visual Studio – I’m using Xamarin Forms for my application, hence Visual Studio). These look like this

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

All works fine until you try to run your application (which requires these permissions) on an Android device with a >= 23 version. Instead, within the debug output you’ll see Security Exceptions around such permissions.

So along with our manifest, we now need to request these permissions within the MainActivity.cs we can write something like

private void CheckPermissions()
{
   ActivityCompat.RequestPermissions(this, new []
   {
      Manifest.Permission.AccessCoarseLocation,
      Manifest.Permission.AccessFineLocation,
      Manifest.Permission.Bluetooth,
      Manifest.Permission.BluetoothAdmin
   }, 1);
}

We might wish to first check whether a permission has already been granted, using code such as

if (ContextCompat.CheckSelfPermission(
   this, Manifest.Permission.AccessCoarseLocation) 
   != Permission.Granted)
{
   // request permission
}

On top of this, we probably want to either inform the user or handle failures to get the requested permissions (for example disabling such functionality), in such cases we override the OnRequestPermissionsResult method within the MainActivity.cs file (i.e. within the FormsAppCompatActivity class)

public override void OnRequestPermissionsResult(
   int requestCode, 
   string[] permissions, 
   Permission[] grantResults)
{
   // we may want to handle failure to get the permissions we require
   // we should handle here, otherwise call the base method
   base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

See Permissions In Xamarin.Android, also see the Android documentation Permissions Overview.