Android 蓝牙连接

Android 蓝牙连接 RxAndroidBle连接库只能扫描出Ble类型设备 使用原生Android扫描出设备获取Mac地址,然后用RxAndroidBle连接 fun scanBleDeviceNative(deviceName: String) { val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager).adapter if (adapter == null || !adapter.isEnabled) { Timber.tag(TAG).w("蓝牙未开启") return } // 如果之前正在扫描,先取消 if (adapter.isDiscovering) adapter.cancelDiscovery() // 监听经典蓝牙发现广播 val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { BluetoothDevice.ACTION_FOUND -> { val device: BluetoothDevice? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java ) } else { @Suppress("DEPRECATION") intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) } device?.let { val name = it.name ?: return if (name.contains(deviceName, ignoreCase = true)) { Timber.tag(TAG) .d("找到设备: $name ${device.address}") // 将经典 BluetoothDevice 转为 RxBleDevice 对象 val bleDevice = rxBleClient.getBleDevice(device.address) // 连接 到设备.... // 停止扫描 try { adapter.cancelDiscovery() } catch (_: Exception) { } context.unregisterReceiver(this) } } } BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> { Timber.tag(TAG).d("扫描结束") context.unregisterReceiver(this) } } } } val filter = IntentFilter(BluetoothDevice.ACTION_FOUND).apply { addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) } context.registerReceiver(receiver, filter) // 启动蓝牙扫描 adapter.startDiscovery() Timber.tag(TAG).d("开始扫描") // 设置 10 秒超时停止扫描 Handler(Looper.getMainLooper()).postDelayed({ try { if (adapter.isDiscovering) adapter.cancelDiscovery() Timber.tag(TAG).d("扫描超时,已停止") context.unregisterReceiver(receiver) } catch (_: Exception) { } }, 10_000) }

2025年11月07日