优化:BluetoothReceiver偶尔崩溃(增加异常捕获) #499

This commit is contained in:
pppscn 2024-07-16 09:28:34 +08:00
parent 9436e3498b
commit ff83a8a5f7

View File

@ -36,28 +36,42 @@ class BluetoothReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) { override fun onReceive(context: Context?, intent: Intent?) {
if (context == null || intent == null) return if (context == null || intent == null) return
when (val action = intent.action) { try {
// 发现设备 when (intent.action) {
BluetoothDevice.ACTION_FOUND -> { BluetoothDevice.ACTION_FOUND -> handleActionFound(intent)
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> handleDiscoveryFinished(context)
device?.let { BluetoothAdapter.ACTION_STATE_CHANGED -> handleStateChanged(context, intent)
BluetoothAdapter.ACTION_SCAN_MODE_CHANGED -> handleScanModeChanged()
BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED -> handleLocalNameChanged()
BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED -> handleConnectionStateChanged()
BluetoothDevice.ACTION_BOND_STATE_CHANGED -> handleBondStateChanged()
BluetoothDevice.ACTION_ACL_CONNECTED -> handleAclConnected(context, intent)
BluetoothDevice.ACTION_ACL_DISCONNECTED -> handleAclDisconnected(context, intent)
}
} catch (e: Exception) {
Log.e(TAG, "Error handling Bluetooth action: ${intent.action}", e)
}
}
// 处理发现设备
private fun handleActionFound(intent: Intent) {
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) ?: return
if (ActivityCompat.checkSelfPermission(App.context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return if (ActivityCompat.checkSelfPermission(App.context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
if (SettingUtils.bluetoothIgnoreAnonymous && it.name.isNullOrEmpty()) return if (SettingUtils.bluetoothIgnoreAnonymous && device.name.isNullOrEmpty()) return
//TODO: 实测这里一台设备会收到两次广播 //TODO: 实测这里一台设备会收到两次广播
Log.d(TAG, "Discovered device: ${it.name} - ${it.address}") Log.d(TAG, "Discovered device: ${device.name} - ${device.address}")
val discoveredDevices = TaskUtils.discoveredDevices val discoveredDevices = TaskUtils.discoveredDevices
discoveredDevices[it.address] = it.name ?: "" discoveredDevices[device.address] = device.name ?: ""
TaskUtils.discoveredDevices = discoveredDevices TaskUtils.discoveredDevices = discoveredDevices
} }
}
// 扫描完成 // 处理扫描完成
BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> { private fun handleDiscoveryFinished(context: Context) {
//TODO: 放在这里去判断是否已经发现某个设备(避免 ACTION_FOUND 重复广播) //TODO: 放在这里去判断是否已经发现某个设备(避免 ACTION_FOUND 重复广播)
Log.d(TAG, "Bluetooth scan finished, discoveredDevices: ${TaskUtils.discoveredDevices}") Log.d(TAG, "Bluetooth scan finished, discoveredDevices: ${TaskUtils.discoveredDevices}")
if (TaskUtils.discoveredDevices.isNotEmpty()) { if (TaskUtils.discoveredDevices.isNotEmpty()) {
handleWorkRequest(context, action, Gson().toJson(TaskUtils.discoveredDevices)) handleWorkRequest(context, BluetoothAdapter.ACTION_DISCOVERY_FINISHED, Gson().toJson(TaskUtils.discoveredDevices))
} }
restartBluetoothService(ACTION_STOP) restartBluetoothService(ACTION_STOP)
@ -69,52 +83,49 @@ class BluetoothReceiver : BroadcastReceiver() {
} }
} }
// 蓝牙状态变化 // 处理蓝牙状态变化
BluetoothAdapter.ACTION_STATE_CHANGED -> { private fun handleStateChanged(context: Context, intent: Intent) {
val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
handleBluetoothStateChanged(state) handleBluetoothStateChanged(state)
handleWorkRequest(context, action, state.toString()) handleWorkRequest(context, BluetoothAdapter.ACTION_STATE_CHANGED, state.toString())
} }
// 蓝牙扫描模式变化 // 处理蓝牙扫描模式变化
BluetoothAdapter.ACTION_SCAN_MODE_CHANGED -> { private fun handleScanModeChanged() {
if (SettingUtils.enableBluetooth) { if (SettingUtils.enableBluetooth) {
restartBluetoothService() restartBluetoothService()
} }
} }
// 本地蓝牙名称变化 // 处理本地蓝牙名称变化
BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED -> { private fun handleLocalNameChanged() {
// handle local name changed logic
} }
// 蓝牙连接状态变化 // 处理蓝牙连接状态变化
BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED -> { private fun handleConnectionStateChanged() {
// handle connection state changed logic
} }
// 蓝牙设备的配对状态变化 // 处理蓝牙设备的配对状态变化
BluetoothDevice.ACTION_BOND_STATE_CHANGED -> { private fun handleBondStateChanged() {
// handle bond state changed logic
} }
// 蓝牙设备连接 // 处理蓝牙设备连接
BluetoothDevice.ACTION_ACL_CONNECTED -> { private fun handleAclConnected(context: Context, intent: Intent) {
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) ?: return
if (device != null) {
Log.d(TAG, "Connected device: ${device.name} - ${device.address}") Log.d(TAG, "Connected device: ${device.name} - ${device.address}")
TaskUtils.connectedDevices[device.address] = device.name TaskUtils.connectedDevices[device.address] = device.name
handleWorkRequest(context, action, Gson().toJson(mutableMapOf(device.address to device.name))) handleWorkRequest(context, BluetoothDevice.ACTION_ACL_CONNECTED, Gson().toJson(mutableMapOf(device.address to device.name)))
}
} }
// 蓝牙设备断开连接 // 处理蓝牙设备断开连接
BluetoothDevice.ACTION_ACL_DISCONNECTED -> { private fun handleAclDisconnected(context: Context, intent: Intent) {
val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) ?: return
if (device != null) {
Log.d(TAG, "Disconnected device: ${device.name} - ${device.address}") Log.d(TAG, "Disconnected device: ${device.name} - ${device.address}")
TaskUtils.connectedDevices.remove(device.address) TaskUtils.connectedDevices.remove(device.address)
handleWorkRequest(context, action, Gson().toJson(mutableMapOf(device.address to device.name))) handleWorkRequest(context, BluetoothDevice.ACTION_ACL_DISCONNECTED, Gson().toJson(mutableMapOf(device.address to device.name)))
}
}
}
} }
// 处理蓝牙状态变化 // 处理蓝牙状态变化
@ -178,6 +189,7 @@ class BluetoothReceiver : BroadcastReceiver() {
App.context.startService(serviceIntent) App.context.startService(serviceIntent)
} }
// 发送任务请求
private fun handleWorkRequest(context: Context, action: String, msg: String) { private fun handleWorkRequest(context: Context, action: String, msg: String) {
val request = OneTimeWorkRequestBuilder<BluetoothWorker>() val request = OneTimeWorkRequestBuilder<BluetoothWorker>()
.setInputData( .setInputData(