I’ve got a problem with finding bluetooth devices.
The only thing I want to do is to log info about bluetooth devices.
I’m using android 7.
I added all necessary permissions.
Here’s the code:
class MainActivity : AppCompatActivity(), AnkoLogger {
lateinit var bleManager: BluetoothManager
lateinit var bleAdapter: BluetoothAdapter
lateinit var bleScanner: BluetoothLeScanner
val REQUEST_BLUETOOTH = 0
val REQUEST_FINE_LOCATION = 1
val ui by lazy { MainUI() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ui.setContentView(this)
bleManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bleAdapter = bleManager.adapter
checkLocationPerm()
checkEnableBluetooth()
ui.scanButton.onClick {
startScan()
}
}
fun checkLocationPerm() {
val perm = PermissionChecker.checkSelfPermission(applicationContext, Manifest.permission.ACCESS_FINE_LOCATION)
if (perm == PermissionChecker.PERMISSION_GRANTED) {
info("Location permission granted")
} else requestEnableLocation()
}
fun requestEnableLocation() = requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
REQUEST_FINE_LOCATION)
fun checkEnableBluetooth() {
if (!bleAdapter.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_BLUETOOTH)
info("Requested user to enable bluetooth.")
}
}
fun startScan() {
bleScanner = bleAdapter.bluetoothLeScanner
var scanResults = mutableMapOf<String?, BluetoothDevice?>()
var bleScanCallback = BleScanCallback(scanResults)
bleScanner.startScan(bleScanCallback)
}
class BleScanCallback(resultMap: MutableMap<String?, BluetoothDevice?>) : ScanCallback(), AnkoLogger {
var resultOfScan = resultMap
override fun onScanResult(callbackType: Int, result: ScanResult?) {
addScanResult(result)
info("I found a ble device ${result?.device?.address}")
}
override fun onBatchScanResults(results: MutableList<ScanResult>?) {
results?.forEach { result -> addScanResult(result) }
}
override fun onScanFailed(errorCode: Int) {
info("Bluetooth LE scan failed. Error code: $errorCode")
}
fun addScanResult(scanResult: ScanResult?) {
val bleDevice = scanResult?.device
val deviceAddress = bleDevice?.address
resultOfScan.put(deviceAddress, bleDevice)
}
}
}