问题
I am creating a Bluetooth scanner app and trying to find the available devices to pair. I have a Bluetooth headset which I am trying to find running the application on android 10.
Permissions are set in manifest
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
App contains a simple button on whose click I start discovery for bluetooth device
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter = bluetoothManager.adapter
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
val bluetoothLeScanner = BluetoothAdapter.getDefaultAdapter().bluetoothLeScanner
scanBluettoth.setOnClickListener({
bluetoothLeScanner.startScan(leScanCallback)
})
Callback for discovery
val leScanCallback: ScanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
super.onScanResult(callbackType, result)
Log.e("device ", "D ".plus(result.device.name))
}
}
Can someone help me out if I am missing something here?
回答1:
Is location on the device turned off? Location has to be enabled for Android 10 to get scan results.
Also remember to also ask for permission
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, PERM);
}
来源:https://stackoverflow.com/questions/65105856/bluetooth-scanner-not-discovering-devices