Per aproximar-nos al tema dels dispositius Bluetooth podem seguir 2 estratègies diferents:
Obtenir aquesta llista és senzill accedint BluetoothAdapter.bondedDevices. En aquest exemple, a més, filtrem els dispositius que poden ser del tipus BLE (Bluetooth Low Emission), però es pot treure el filtre si cal:
fun updatePairedDevices() { // empty list dataset.clear() // update list val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() for( elem in bluetoothAdapter.bondedDevices.filter { device -> // Filtrar per dispositius BLE device.type == BluetoothDevice.DEVICE_TYPE_LE || device.type == BluetoothDevice.DEVICE_TYPE_DUAL || device.type == BluetoothDevice.DEVICE_TYPE_UNKNOWN } ) { // afegim element al dataset dataset.add( elem ) } }
La gestió de permisos del Bluetooth és una part més engorrosa.
Primer de tot, declarar els permisos estàtics a AndroidManifest.xml:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Per a Android 12 o superior --> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
Seguidament, necessitarem al nostre codi demanar els permisos dinàmics. Abans de cridar a la funció updatePairedDevices() ja vista abans, haurem de fer una funció «wrapper» que abans s'asseguri que els permisos estan ben gestionats.
private val REQUEST_CODE_BLUETOOTH = 100 // es pot posar un nombre aleatori no emprat en cap altre lloc private fun requestBluetoothPermissionAndUpdate() { val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Android 12+ requereix BLUETOOTH_CONNECT Manifest.permission.BLUETOOTH_CONNECT } else { // Versions anteriors Manifest.permission.BLUETOOTH } if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { // Demanar el permís ActivityCompat.requestPermissions( this, arrayOf(permission), REQUEST_CODE_BLUETOOTH ) } else { // Permís ja concedit - llegir dispositius updatePairedDevices() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == REQUEST_CODE_BLUETOOTH) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permís concedit - llegir dispositius updatePairedDevices() } else { // Permís denegat Toast.makeText(this, "Permís necessari per a llegir Bluetooth", Toast.LENGTH_SHORT).show() } } }