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

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

//搜索设备

<

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Studio中连接HC-05蓝牙模块,需要使用Android蓝牙API和串口通信协议,具体步骤如下: 1. 在AndroidManifest.xml文件中添加蓝牙权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> ``` 2. 在应用程序中使用BluetoothAdapter类来获取本地蓝牙适配器: ```java BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ``` 3. 使用BluetoothAdapter对象来搜索HC-05蓝牙模块: ```java bluetoothAdapter.startDiscovery(); ``` 4. 连接HC-05蓝牙模块。首先需要获取HC-05蓝牙模块的MAC地址,然后使用BluetoothDevice类来连接蓝牙模块: ```java String mac = "00:11:22:33:44:55"; // HC-05蓝牙模块的MAC地址 BluetoothDevice device = bluetoothAdapter.getRemoteDevice(mac); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); ``` 其中,uuid是HC-05蓝牙模块服务的UUID,可以在HC-05模块的说明书中找到。 5. 使用IO流进行数据的传输和通信。可以使用InputStream和OutputStream来进行数据的读写操作: ```java InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); byte[] buffer = new byte[1024]; int bytes; bytes = inputStream.read(buffer); outputStream.write(buffer, 0, bytes); ``` 6. 最后,在应用程序退出时需要关闭蓝牙连接: ```java socket.close(); ``` 以上是Android Studio连接HC-05蓝牙模块的基本步骤,具体的实现过程需要根据应用程序的需求和实际情况进行相应的调整和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值