Android BLE改进Kotlin中ScanCallback()的权限检查

Android BLE改进Kotlin中ScanCallback()的权限检查,android,kotlin,bluetooth,bluetooth-lowenergy,Android,Kotlin,Bluetooth,Bluetooth Lowenergy,我正在开发一个带有可扩展设备的小应用程序。有时扫描回调可以正常工作,我可以找到设备,但有时扫描回调不工作,我想知道我的代码是否有问题,或者我的权限检查是否有问题 这是我的密码: override fun onCreate(savedInstanceState: Bundle?) { if (!isBLESupported(this)) { Toast.makeText(this, "This device doesn't support bluetooth", Toas

我正在开发一个带有可扩展设备的小应用程序。有时扫描回调可以正常工作,我可以找到设备,但有时扫描回调不工作,我想知道我的代码是否有问题,或者我的权限检查是否有问题

这是我的密码:

override fun onCreate(savedInstanceState: Bundle?) {

    if (!isBLESupported(this)) {
        Toast.makeText(this, "This device doesn't support bluetooth", Toast.LENGTH_SHORT).show()
        finish()
    } else {
        if (!mBtAdapter!!.isEnabled) {
            val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH)
        }
    }

    adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, macList)
    list_view.adapter = adapter

private val lightUUID = UUID.fromString("0000ffb0-0000-1000-8000-00805f9b34fb")
scan_button.setOnClickListener {
        scanForDeviceWithFilter(lightUUID)
    }
}

private fun scanForDeviceWithFilter(serviceUUID: UUID) {

    val uuid = ParcelUuid(id)
    val filter = ScanFilter.Builder().setServiceUuid(uuid).build()
    val filters = listOf(filter)
    val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build()

   checkBTPermissions()
    mBtAdapter!!.bluetoothLeScanner.startScan(filters, settings, scanDevicesCallback)
}

  private val scanDevicesCallback = object : ScanCallback() {

    override fun onScanResult(callbackType: Int, result: ScanResult?) {
        result?.let {
            if (!macList.contains(result.device.name.toString())) {
                macList.add(result.device.name.toString())
                adapter.notifyDataSetChanged()
            }
            Log.d(TAG, "device found:${result.device}")
        }

    }

    override fun onScanFailed(errorCode: Int) {
        Log.d(TAG, "Scan failed $errorCode")
    }
}

private fun isBLESupported(context: Context): Boolean {
    return BluetoothAdapter.getDefaultAdapter() != null && context.packageManager.hasSystemFeature(
        PackageManager.FEATURE_BLUETOOTH_LE
    )
}

private fun checkBTPermissions() {
    val permissionCheck = checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION")
    if (permissionCheck != 0) {
        requestPermissions(
            arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1001
        )
    }
}

init {
    mBtAdapter = BluetoothAdapter.getDefaultAdapter()
}