Android BLE蓝牙连接代码
时间: 2023-07-28 09:10:09 浏览: 267
以下是一个简单的 Android BLE 蓝牙连接代码示例:
```
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothGatt bluetoothGatt;
// 初始化 BluetoothManager 和 BluetoothAdapter
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
// 扫描设备并连接
bluetoothAdapter.startLeScan(new UUID[]{MY_UUID}, mLeScanCallback);
bluetoothDevice.connectGatt(this, false, mGattCallback);
// 扫描设备的回调函数
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
if (device.getAddress().equals(DEVICE_ADDRESS)) {
bluetoothDevice = device;
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
};
// 连接设备的回调函数
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
bluetoothGatt = gatt;
// 连接成功,开始发现服务
bluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
// 连接断开
bluetoothGatt.close();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// 发现服务成功,可以开始进行操作
BluetoothGattService service = gatt.getService(SERVICE_UUID);
BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_UUID);
characteristic.setValue("Hello, BLE!");
gatt.writeCharacteristic(characteristic);
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
// 写入特征值成功
}
};
```
需要注意的是,此示例中的 UUID、DEVICE_ADDRESS、SERVICE_UUID 和 CHARACTERISTIC_UUID 都需要根据实际情况进行替换。
阅读全文