这篇文章跟我们下面要做的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);
//搜索设备

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

被折叠的 条评论
为什么被折叠?



