Android 蓝牙设备(HC-05)搜索,连接,通信

本文介绍了如何在Android应用中搜索、连接和通信与HC-05蓝牙模块。首先获取并遍历已配对的蓝牙设备,接着注册广播接收器以监听设备发现和搜索完成。在搜索到新设备时,将其添加到列表并尝试连接。成功连接后,启动接收数据的线程。当接收到数据时,更新日志并展示在ListView中。

这篇文章跟我们下面要做的HC-05蓝牙模块通信有关。

首先要能在手机上搜索到HC-05,然后相互发送消息。

首先是搜索蓝牙设备的代码:

private BluetoothAdapter mBluetoothAdapter;

if (mBluetoothAdapter == null) {

mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

}

//已配对的蓝牙设备

Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();

if (devices.size() > 0) {

for (BluetoothDevice bluetoothDevice : devices) {

// 保存到arrayList集合中

ItemInfo item = new ItemInfo();

item.name = bluetoothDevice.getName();

item.address = bluetoothDevice.getAddress();

if (!data.contains(item) && !TextUtils.isEmpty(item.name)) {

data.add(item);

//已配对的连接设备

new Thread(()->{

connectDevice(item);

}).start();

}

}

}

// 因为蓝牙搜索到设备和完成搜索都是通过广播来告诉其他应用的

// 这里注册找到设备和完成搜索广播

IntentFilter filter = new IntentFilter();

filter.addAction(BluetoothDevice.ACTION_FOUND); // 用BroadcastReceiver来取得搜索结果

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);

filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

mActivity.registerReceiver(receiver, filter);

//搜索设备

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值