Java安卓蓝牙开发基础
蓝牙技术作为短距离无线通信的重要方式,在安卓开发中广泛应用于设备连接、数据传输等场景,本文将详细介绍基于Java的安卓蓝牙开发流程,包括蓝牙权限配置、设备扫描、连接管理及数据传输等核心内容,帮助开发者快速掌握蓝牙开发技能。

蓝牙权限与配置
在安卓开发中,使用蓝牙功能首先需要在AndroidManifest.xml中声明必要的权限,对于蓝牙经典设备(BLE),需添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 用于扫描设备位置信息 ``` 若需支持蓝牙低功耗(BLE),还需添加: ```xml <uses-feature android:name="android.hardware.bluetooth_le" android:required="true" />
需在代码中动态检查蓝牙是否开启,若未开启则引导用户开启:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
} else if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
扫描与发现蓝牙设备
扫描蓝牙设备是连接的第一步,通过BluetoothAdapter的startDiscovery()方法开始扫描,并通过BroadcastReceiver监听扫描结果:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 获取设备名称和地址
String deviceName = device.getName();
String deviceAddress = device.getAddress();
// 添加到设备列表
}
}
};
注意:扫描完成后需取消扫描以节省资源:

bluetoothAdapter.cancelDiscovery();
建立蓝牙连接
蓝牙连接分为经典蓝牙和BLE两种方式,经典蓝牙通过Socket通信,而BLE使用BluetoothGatt,此处以经典蓝牙为例:
- 作为服务器端(蓝牙串口):
BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord("BluetoothApp", UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); BluetoothSocket socket = serverSocket.accept(); // 阻塞等待连接 - 作为客户端:
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); socket.connect();连接成功后,可通过
InputStream和OutputStream进行数据传输:OutputStream outputStream = socket.getOutputStream(); outputStream.write("Hello Bluetooth".getBytes());
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int bytes = inputStream.read(buffer);
String receivedData = new String(buffer, 0, bytes);
#### 四、蓝牙低功耗(BLE)开发
BLE开发主要涉及`BluetoothGatt`、`BluetoothGattCallback`等类,核心步骤如下:
1. **扫描BLE设备**:
```java
BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
ScanFilter filter = new Scan.Builder().setServiceUuid(new ParcelUuid(UUID.fromString("YOUR_SERVICE_UUID"))).build();
ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
scanner.startScan(Arrays.asList(filter), settings, scanCallback);
-
连接设备:

BluetoothGatt gatt = device.connectGatt(context, false, gattCallback);
-
读写特征值:
BluetoothGattCharacteristic characteristic = gatt.getService(serviceUUID).getCharacteristic(charUUID); characteristic.setValue("Data".getBytes()); gatt.writeCharacteristic(characteristic);BluetoothGattCallback用于处理连接状态、服务发现等事件:private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { gatt.discoverServices(); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { // 获取服务并读取特征值 } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { // 处理读取数据 } };
蓝牙开发注意事项
- 权限管理:安卓6.0及以上需动态申请位置权限,否则无法扫描设备。
- 线程安全:蓝牙操作(如连接、读写)应在主线程外执行,避免阻塞UI。
- 资源释放:断开连接时需关闭
Socket、InputStream和OutputStream,并注销BroadcastReceiver。 - 兼容性:不同安卓版本对蓝牙API的支持可能存在差异,需进行版本适配。
Java安卓蓝牙开发涉及权限配置、设备扫描、连接管理和数据传输等多个环节,开发者需根据实际需求选择经典蓝牙或BLE方案,并注意权限管理和资源释放,通过合理运用BluetoothAdapter、BluetoothSocket和BluetoothGatt等核心类,可高效实现蓝牙通信功能,在实际开发中,建议结合官方文档和开源项目,进一步优化代码的稳定性和兼容性。




















