Android 蓝牙终端交互管理

本文介绍了一种蓝牙操作的封装方法,包括搜索蓝牙设备、配对、发送与接收消息等功能,并提供了一个完整的示例链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


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

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值