从零开始学Android蓝牙编程:轻松上手,实现设备间互联互通

2026-11-09 0 阅读

蓝牙技术简介

蓝牙技术是一种无线通信技术,它允许设备在短距离内进行数据交换。在Android开发中,蓝牙编程是一个非常有用的技能,可以帮助开发者实现设备间的互联互通。本文将从零开始,逐步引导你掌握Android蓝牙编程的基础知识,并最终实现设备间的通信。

环境搭建

在进行蓝牙编程之前,我们需要搭建一个开发环境。以下是搭建Android蓝牙开发环境的步骤:

  1. 安装Android Studio。
  2. 创建一个新的Android项目。
  3. 确保项目中的最低API级别支持蓝牙功能。
  4. 在build.gradle文件中添加蓝牙依赖库。
dependencies {
    implementation 'androidx.bluetooth:bluetooth:1.2.0'
}

蓝牙基础概念

在开始编程之前,我们需要了解一些蓝牙基础概念:

  • 蓝牙设备:包括蓝牙手机、蓝牙耳机、蓝牙鼠标等。
  • 蓝牙角色:在蓝牙通信过程中,设备可以扮演两种角色,即中心设备(Central)和外围设备(Peripheral)。
  • 蓝牙服务:服务是一组可以远程访问的功能。
  • 蓝牙特征:特征是服务中的一个功能。

蓝牙编程步骤

1. 启用蓝牙

在开始蓝牙编程之前,我们需要确保蓝牙已启用。以下是如何在Android中启用蓝牙的示例代码:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    // 蓝牙不可用
} else if (!bluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

2. 扫描蓝牙设备

在获取到蓝牙适配器后,我们可以扫描附近的蓝牙设备。以下是如何扫描蓝牙设备的示例代码:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothScanner scanner = bluetoothAdapter.getBluetoothScanner();
Set<BluetoothDevice> devices = scanner.getBondedDevices();
if (devices.isEmpty()) {
    // 没有发现已配对的设备
} else {
    for (BluetoothDevice device : devices) {
        // 处理已配对的设备
    }
}

3. 连接蓝牙设备

扫描到蓝牙设备后,我们可以尝试连接它。以下是如何连接蓝牙设备的示例代码:

BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();

4. 通信

连接成功后,我们可以进行数据传输。以下是如何发送和接收数据的示例代码:

DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeBytes("Hello, Bluetooth!");

DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String message = inputStream.readUTF();

总结

通过本文的学习,相信你已经对Android蓝牙编程有了初步的了解。在实际开发过程中,还需要掌握更多的蓝牙编程技巧和注意事项。希望本文能帮助你轻松上手Android蓝牙编程,实现设备间的互联互通。

分享到: