Bluetooth pemissions in Android Studio

Viewed 41

I want to request BLUETOOTH_SCAN and BLUETOOTH_CONNECT permission. Could anyone tell me how should I do that in Kotlin? I have this piece of code but it always tells permission denied.

class MainActivity : AppCompatActivity() {

 var requestBluetooth = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == RESULT_OK) {
        Toast.makeText(this, "granted", Toast.LENGTH_SHORT).show()
    }else{
        Toast.makeText(this, "denied", Toast.LENGTH_SHORT).show()
    }
}

private val requestMultiplePermissions =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        permissions.entries.forEach {
            Log.d("test", "${it.key} = ${it.value}")
          }
    }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val button = findViewById<Button>(R.id.button) // just a simple button from XML file

    button.setOnClickListener  { 

        // for android 12
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requestMultiplePermissions.launch(arrayOf(
                Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.BLUETOOTH_CONNECT))
          }
        else{
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            requestBluetooth.launch(enableBtIntent)
          }

    }

}

}

1 Answers

Because I am not yet well-versed in Kotlin (and I expect you to be able to easily convert the Java codes into Kotlin), I'll just show you how to request the dangerous Manifest.permission.BLUETOOTH_CONNECT permission every time we want to access the list of paired Bluetooth devices:

    public static final int PERMISSIONS_REQUEST_BLUETOOTH_CONNECT = 101; //the int value must be unique

    public boolean checkBluetoothConnectPermission(Activity activity) {
        boolean permitted = false;

        Boolean bluetoothAlreadyGranted = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) ? 
            ActivityCompat.checkSelfPermission(activity, 
                Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED: true;

        Log.i(IMapView.LOGTAG, 
            String.format("PERMISSION: checkBluetoothPermission(%s) bluetoothAlreadyGranted=%s", 
                activity.getClass().getSimpleName(), 
                bluetoothAlreadyGranted));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Check for permission
            if (!bluetoothAlreadyGranted.booleanValue()) {

                bluetoothAlreadyGranted = ActivityCompat.shouldShowRequestPermissionRationale(activity, 
                    Manifest.permission.BLUETOOTH_CONNECT);

                // Check for permission
                if (bluetoothAlreadyGranted.booleanValue()) {

                    new AlertDialog.Builder(MainApp.getCurrentActivity(), R.style.AppCompatAlertDialogStyle)
                            .setTitle(activity.getString(R.string.bluetooth_connect_rational_title, 
                                activity.getString(R.string.app_name_flavor)))
                            .setMessage(activity.getString(R.string.bluetooth_connect_rational_message, 
                                activity.getString(R.string.app_name_flavor)))
                            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ActivityCompat.requestPermissions(activity,
                                            new String[]{Manifest.permission.BLUETOOTH_CONNECT},
                                            PERMISSIONS_REQUEST_BLUETOOTH_CONNECT);
                                }
                            })
                            .create()
                            .show();
                } else {
                    ActivityCompat.requestPermissions(activity,
                            new String[]{Manifest.permission.BLUETOOTH_CONNECT},
                            PERMISSIONS_REQUEST_BLUETOOTH_CONNECT);
                }
            } else {
                permitted = true;
            }
        } else {
            permitted = true;
        }

        return permitted;
    }

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

        // Check if permission was granted
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; //@TODO you need to check which permission from the array to get the granted status for the matched request code...

        switch (requestCode) {

            case PERMISSIONS_REQUEST_BLUETOOTH_CONNECT: {
                //do whatever you want here
            }
            break;

        }
    }                

In the Android manifest, the following entry shall be provided:

<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />

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

The same shall apply for the dangerous Manifest.permission.BLUETOOTH_SCAN permission with a different intent request code.

Related