1

fun connect(address: String?): Boolean { if (mBluetoothAdapter == null || address == null) { return false } try { if(BluetoothAdapter.checkBluetoothAddress(address)) { device = mBluetoothAdapter?.getRemoteDevice(address) } else { Toast.makeText(this, "Invalid MAC: Address", Toast.LENGTH_LONG).show() }

    } catch (e: IllegalArgumentException) {
        e.printStackTrace()
    } catch (e: IllegalStateException) {
        e.printStackTrace()
    }

    if (device == null) {
     
        return false
    }
    mBluetoothGatt = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
        device?.connectGatt(
            this, false, mGattCallback,
            BluetoothDevice.TRANSPORT_LE
        )
    } else {
        device?.connectGatt(this, false, mGattCallback)
    }
    Log.d(TAG, "Trying to create a new connection.")

    mBluetoothDeviceAddress = address
    mConnectionState = STATE_CONNECTING
    return true

}
lakshmi
  • 45
  • 5
  • You write the error perfectly fine - Fatal Exception: java.lang.SecurityException Need android.permission.BLUETOOTH_CONNECT Just added the permission required to the manifest and make sure it's given to the app – Dan Baruch Oct 25 '22 at 08:15
  • @DanBaruch yes i have added it in the manifest even though it is asking at the run time.if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {return}.SDK suggesting this but then app not connecting to thee BLE device. – lakshmi Oct 25 '22 at 08:20
  • Then provide code example and the error log in full to investigate further – Dan Baruch Oct 25 '22 at 08:21
  • @DanBaruch crash getting while device?.connectGatt( this, false, mGattCallback, BluetoothDevice.TRANSPORT_LE ) calling this. Can you please tell me how i can fix this – lakshmi Oct 25 '22 at 08:40

1 Answers1

1

So if you already requested the Bluetooth permission in the manifest next thing to do is to ask the user to provide it to the app. An example how to do this is written in Kotlin:

fun getBluetoothPermission() {
    // Check if SDK is 31+
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        requestPermission.launch(Manifest.permission.BLUETOOTH_CONNECT)
    } else {
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        requestBluetooth.launch(enableBtIntent)
    }
}

private var requestBluetooth = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == RESULT_OK) {
        //granted
    } else {
        //deny
    }
}

private val requestPermission =
        registerForActivityResult(ActivityResultContracts.RequestPermissions()) { permission -> Log.d(permission) }

N.B. - not tested but should work.

EDIT:

You can also do for multiple permissions:

fun getBluetoothPermission() {
    // Check if SDK is 31+
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        requestMultiplePermissions.launch(arrayOf(
                            Manifest.permission.BLUETOOTH_LE,
                            Manifest.permission.BLUETOOTH_CONNECT))
    } else {
        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        requestBluetooth.launch(enableBtIntent)
    }
}

private val requestMultiplePermissions =
                registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
                    permissions.entries.forEach {
                        Log.d("Permission: ", "${it.key} = ${it.value}")
                    }
}
Top4o
  • 547
  • 6
  • 19
  • Hi, the above code i have tried and it is not working for higher versions above 11.Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with `checkPermission`) or explicitly handle a potential `SecurityException`. this is the exact exception that iam getting. – lakshmi Oct 25 '22 at 13:11
  • You can do if (checkSelfPermission("The permission needed") == PackageManager.PERMISSION_GRANTED) before you execute the code snippet which throws the exception. – Top4o Oct 25 '22 at 14:06
  • Hi sorry these were not working bluetooth is not even getting turned on when i run on 12 and 12+ versions. It is asking for the permissions to access nearby devices and only once at the first installation time. – lakshmi Oct 26 '22 at 10:29