面试题答案
一键面试初始化蓝牙适配器
- 获取蓝牙适配器
- 代码示例:
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
val bluetoothAdapter = bluetoothManager.adapter
- **可能遇到的错误**:设备不支持蓝牙功能。
- **处理方式**:通过检查 `bluetoothAdapter` 是否为 `null` 判断,若为 `null`,提示用户设备不支持蓝牙。
2. 检查蓝牙是否开启 - 代码示例:
if (!bluetoothAdapter.isEnabled) {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}
- **可能遇到的错误**:用户拒绝开启蓝牙。
- **处理方式**:在 `onActivityResult` 中检查返回结果,若用户拒绝,根据业务需求决定是否继续提示用户开启或结束蓝牙相关操作。
扫描蓝牙低能耗设备
- 注册广播接收器
- 代码示例:
val bluetoothReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (BluetoothDevice.ACTION_FOUND == action) {
val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
// 处理找到的设备
}
}
}
val filter = IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(bluetoothReceiver, filter)
- **可能遇到的错误**:广播注册失败。
- **处理方式**:检查权限是否正确申请,并且在合适的生命周期内注册广播,如在 `onCreate` 中注册。
2. 开始扫描 - 代码示例:
bluetoothAdapter.startDiscovery()
- **可能遇到的错误**:扫描失败,例如没有获取到合适的权限。
- **处理方式**:确保在 `AndroidManifest.xml` 中申请了 `ACCESS_COARSE_LOCATION` 或 `ACCESS_FINE_LOCATION` 权限(Android 6.0 及以上),并在运行时请求权限。
连接蓝牙低能耗设备
- 获取
BluetoothGatt
对象- 代码示例:
val bluetoothGatt = bluetoothDevice.connectGatt(this, false, object : BluetoothGattCallback() {
// 实现回调方法
})
- **可能遇到的错误**:连接失败,可能因为设备距离过远、设备不支持 BLE 等。
- **处理方式**:在 `onConnectionStateChange` 回调中处理连接失败情况,如提示用户检查设备状态或距离,或重新扫描设备。
2. 发现服务和特征 - 代码示例:
bluetoothGatt.discoverServices()
- **可能遇到的错误**:发现服务失败。
- **处理方式**:在 `onServicesDiscovered` 回调中处理失败情况,可能需要重新连接设备或检查设备是否正常工作。
数据交互
- 读取特征值
- 代码示例:
val characteristic: BluetoothGattCharacteristic? = // 获取到的特征对象
bluetoothGatt.readCharacteristic(characteristic)
- **可能遇到的错误**:读取失败,可能由于设备连接不稳定等原因。
- **处理方式**:在 `onCharacteristicRead` 回调中处理失败情况,可尝试重新读取或检查连接状态。
2. 写入特征值 - 代码示例:
val characteristic: BluetoothGattCharacteristic? = // 获取到的特征对象
characteristic.value = "data to write".toByteArray()
bluetoothGatt.writeCharacteristic(characteristic)
- **可能遇到的错误**:写入失败,可能由于权限问题或设备不支持写入。
- **处理方式**:在 `onCharacteristicWrite` 回调中处理失败情况,检查特征的权限以及设备是否支持写入操作。
关闭连接
- 断开连接并关闭
BluetoothGatt
- 代码示例:
bluetoothGatt.disconnect()
bluetoothGatt.close()
- **可能遇到的错误**:关闭失败,可能由于连接处于不稳定状态。
- **处理方式**:在合适的生命周期方法中调用关闭操作,如在 `onDestroy` 中,并且捕获可能的异常进行处理。同时可添加重试逻辑。