android - 如果用户拒绝打开蓝牙,则退出 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!!!")
}
}
}
解决方案
只是finish()
在里面打电话
推荐阅读
- maven - 包导入 org.apache.storm.hbase.* 不存在
- reactjs - 用户选择的日期不显示在输入框中
- android - 将小部件直接放在 Row 小部件下方
- c# - 如何在 Devexpress XtraOpenFileDialog 中禁用右键单击?
- html - 如何通过 golang 创建的 HTML 页面发送图像链接
- session - 水平缩放 JSF 2.3 应用程序
- regex - 不应允许允许在电子邮件验证中连续使用特殊字符
- angular - 带去抖动的点击不会进入订阅
- java - 使用签名哈希保护 Android 应用
- android - 如何在单击按钮时以全屏横向模式显示布局的任何部分?