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

main
pppscn 2 months ago
parent 9436e3498b
commit ff83a8a5f7

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

Loading…
Cancel
Save