Home > Software design >  How to detect if user denied ask for switch on bluetooth
How to detect if user denied ask for switch on bluetooth

Time:03-08

How to detect when user didn't allow for open bluetooth?

   if(!isBluetoothOpen()) {
        val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        if (isPermissionGranted()) {
            startActivityForResult(
                enableBluetoothIntent,
                REQUEST_ENABLE_BLUETOOTH
            )
        }

CodePudding user response:

As per documentation https://developer.android.com/reference/android/bluetooth/BluetoothAdapter

Notification of the result of this activity is posted using the Activity.onActivityResult(int, int, Intent) callback. The resultCode will be Activity.RESULT_OK if Bluetooth has been turned on or Activity.RESULT_CANCELED if the user has rejected the request or an error has occurred.

Code:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
        when (resultCode) {
            Activity.RESULT_OK -> { // User approved permission }
            Activity.RESULT_CANCELED -> { // User rejected permission }
        }
    }
}
  • Related