Android 蓝牙终端交互管理

温馨提示:本文主要针对蓝牙终端操作,其他设备暂未测试过。


封装了一系列的蓝牙操作:

1、搜索蓝牙

现已封装为类,可直接调用:BluetoothDeviceDialog

搜索总共分为两步:

(1)开始搜索

BluetoothAdapter.getDefaultAdapter().startDiscovery()

(2)注册播放接收数据

private fun initBluetooth() {
    val intentFilter = IntentFilter()
    intentFilter.addAction(BluetoothDevice.ACTION_FOUND)
    intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
    context.registerReceiver(receiver, intentFilter)
}
private var receiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            BluetoothDevice.ACTION_FOUND -> {//找到设备
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                when (device.bondState) {
                    BluetoothDevice.BOND_BONDED -> Unit
                    else -> if (!holder.adapter.dataList.contains(device)) holder.adapter.add(device)
                }
            }
            BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {//搜索完成
                holder.recyclerView.refreshComplete()
                if (holder.adapter.itemCount <= 0)
                    showToast("未找到设备")
            }
        }
    }
}

2、配对蓝牙

BluetoothChatService.connect()

3、发送消息

BluetoothChatService.write()

4、接收消息


现已将操作封闭为类BluetoothChatService.java,由于代码太多就不贴出来了,请移到Github上查看

完整的实例:Demo链接:https://github.com/SpringSmell/quick.library/blob/master/app/src/main/java/com/example/chriszou/quicksample/ui/bluetooth/BluetoothChatService.java

猜你喜欢

转载自blog.csdn.net/Fy993912_chris/article/details/80540516