首页 > 解决方案 > 如果用户拒绝打开蓝牙,则退出 Android 应用程序

问题描述

我有一个 Kotlin 应用程序,它检查蓝牙适配器是打开还是关闭。如果蓝牙适配器关闭,应用程序会请求用户允许设备上的蓝牙。

问题是:当用户按下允许按钮时,onActivityResult回调打印出允许使用蓝牙。但是如果用户按下拒绝按钮,onActivityResult回调不会打印任何内容。看起来onActivityCallback只能对用户允许蓝牙或发生错误做出反应。

我需要实现以下功能:如果用户拒绝蓝牙请求(按拒绝按钮),应用程序需要退出。有没有办法实现它?

以下是我创建蓝牙适配器实例并请求用户允许使用蓝牙的方法:

// 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
        }
    }

该函数请求用户允许蓝牙:

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

这是我如何覆盖onActivityResult函数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!!!")
            }
        }
    }

标签: androidkotlinandroid-permissionsandroid-bluetooth

解决方案


只是finish()在里面打电话


推荐阅读