2

I have a Kotlin application, which checks whether Bluetooth adapter is turned on or turned off. If the Bluetooth adapter is turned off, the application requests user to allow Bluetooth on the device.

The problem is: when user pushes Allow button, onActivityResult callback prints that Bluetooth is allowed to be used. But if user pushes Deny button, onActivityResult callback prints nothing. It looks like onActivityCallback can react only either user allows Bluetooth or error occurs.

I need to implement the following feature: if user denies Bluetooth request (press Deny button), the application needs to exit. Is there any way to implement it?

Here is how I create Bluetooth adapter instance and request user to allow Bluetooth usage:

// Create bluetooth adapter instance
    val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
        val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothManager.adapter
    }

// Check if bluetooth is turned on, otherwise request user to turn it on
    var bluetooth_requested = false
    while (bluetoothAdapter != null && bluetoothAdapter!!.isDisabled) {
        if (!bluetooth_requested) {
            SetupBLE(bluetoothAdapter)
            bluetooth_requested = true
        }
    }

The function requests user to allow Bluetooth:

fun MainActivity.SetupBLE(bluetoothAdapter: BluetoothAdapter?) {
    val blueToothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
    ActivityCompat.startActivityForResult( this, blueToothIntent, REQUEST_ENABLE_BT, null )
}

Here is how I overrided onActivityResult fuction in MainActivity

// Overrided onActivityResult callback
    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == RESULT_OK) {
                Log.d("onActivityResult", "The result is Allow!!!")
            } else {
                Log.d("onActivityResult", "The result is Deny!!!")
            }
        }
    }
  • check this https://stackoverflow.com/questions/9693755/detecting-state-changes-made-to-the-bluetoothadapter – hemen Jul 17 '20 at 10:28

1 Answers1

3

just call finish() inside else