轻松上手Android蓝牙编程:从基础到实战全攻略

2026-08-12 0 阅读

了解蓝牙技术

在开始Android蓝牙编程之前,我们首先需要了解什么是蓝牙技术。蓝牙(Bluetooth)是一种无线技术标准,旨在实现固定设备、移动设备和个人设备之间的短距离通信。它利用无线电波在设备之间传输数据,广泛应用于无线耳机、鼠标、键盘、打印机等。

环境搭建

1. 安装Android Studio

首先,你需要安装Android Studio,这是Google官方推荐的Android开发工具。下载并安装完成后,打开Android Studio,创建一个新的项目。

2. 添加蓝牙权限

在AndroidManifest.xml文件中,添加以下权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

3. 添加依赖库

在build.gradle文件中,添加以下依赖库:

dependencies {
    implementation 'androidx.core:core-ktx:1.6.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
    implementation 'androidx.navigation:navigation-fragment-ktx:2.3.1'
    implementation 'androidx.navigation:navigation-ui-ktx:2.3.1'
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'org.json:json:20210307'
}

蓝牙基础

1. 蓝牙设备扫描

要扫描附近的蓝牙设备,可以使用BluetoothAdapter和BluetoothDevice类。以下是一个简单的示例:

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

for (BluetoothDevice device : pairedDevices) {
    Log.d("Bluetooth", "已配对的设备:" + device.getName() + ", 地址:" + device.getAddress());
}

2. 连接蓝牙设备

连接蓝牙设备需要使用BluetoothSocket。以下是一个简单的示例:

BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice("设备地址");
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("服务UUID"));
socket.connect();

3. 数据传输

连接成功后,可以使用DataOutputStream和DataInputStream进行数据传输。以下是一个简单的示例:

DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream inputStream = new DataInputStream(socket.getInputStream());

outputStream.writeUTF("Hello, Bluetooth!");
String message = inputStream.readUTF();
Log.d("Bluetooth", "接收到的消息:" + message);

outputStream.close();
inputStream.close();
socket.close();

实战案例

1. 蓝牙心率监测器

这个案例展示了如何使用蓝牙连接心率监测器,并实时显示心率数据。

2. 蓝牙遥控器

这个案例展示了如何使用蓝牙连接遥控器,并实现控制Android设备的功能。

总结

通过本文的学习,相信你已经对Android蓝牙编程有了初步的了解。在实际开发过程中,还需要不断学习和实践,才能熟练掌握蓝牙编程技术。祝你编程愉快!

分享到: