1

I'm developing an android app using kotlin. When I write some logic about scanning BLE devices, no matter what I wanna do, it needs permission. For example, in this function, I ask for permissions.


private fun startBleScan() {
    if (Build.VERSION.SDK_INT >= 21 && !isLocationPermissionGranted) {
        requestLocationPermission()
    }

    if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.BLUETOOTH_SCAN
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        requestBleScanPermission()
    }
    bleScanner.startScan(scanFilters, scanSettings, scanCallback)
    }

But when I wanna working with stopBleScan, it also needs permissions.(I haven't add yet, now ide tells me to add permissions)

private fun stopBleScan() {
    bleScanner.startScan(scanCallback)
}

At last, when I wanna use result.device.name, ide also tells me it needs permission.(Without permission, I can only use result.device, I don't know why).

private val scanCallback = object : ScanCallback() {
    override fun onScanResult(callbackType: Int, result: ScanResult) {
        with(result.device) {
            Log.i("ScanCallback", "$name") // ide tells me it needs permission, this line doesn't work
            foundDevice = true
        }
    }
}

Is there any solution, so I can only ask permissions for one time, I think it is normal otherwise do it everytime. I'm really new to kotlin and BLE, please help me, Thank you in advance!

Edric
  • 24,639
  • 13
  • 81
  • 91
Harvey Xie
  • 81
  • 4
  • If I understand correctly, and it is the IDE signalling you that the function requires some permission, you can simply add the annotation `@RequiresPermission("android.permission.PERMISSION_NAME")` to the functions, or suppress the warning with `@SuppressLint("MissingPermission")`. – Lorenzo Felletti Nov 08 '22 at 14:00

1 Answers1

1

In order to BLE scan for devices on Android, several permissions need to be added to the manifest file (AndroidManifest.xml) as follows:-

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

This is in addition to needing to request permission from the user dynamically. Have a look at the links below for more information:-

Youssif Saeed
  • 11,789
  • 4
  • 44
  • 72