Ble蓝牙API
1.获取蓝牙管理器
- BluetoothManager buetoothManage = getSystemService(Context.BLUETOOTH_SERVICE);
2.获取蓝牙适配器
- BlueToothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
3.获取蓝牙扫描器
- bleScanner = bluetoothAdapter.getBluetoothLeScanner();
- bleScanner.startScan(scanCallback);
// BLE扫描回调
private final ScanCallback scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
BluetoothDevice device = result.getDevice();
String deviceName = device.getName();
// 过滤设备名称
if (deviceName != null && deviceName.contains(DEVICE_NAME_FILTER) &&
!deviceList.contains(device)) {
deviceList.add(device);
devicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
statusText.setText("扫描失败: " + errorCode);
scanning = false;
btnScan.setText("扫描设备");
}
};
4.连接设备
BluetoothGatt bluetoothGatt ;
private void connectDevice() {
bluetoothGatt = selectedDevice.connectGatt(this, false, gattCallback);
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
/// 监听蓝牙连接
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothGatt.STATE_CONNECTED) {
runOnUiThread(() -> {
statusText.setText("已连接,发现服务中...");
});
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
runOnUiThread(() -> {
statusText.setText("已断开连接");
});
}
}
/// 发现BluetoothGatt服务
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
List<BluetoothGattService> gattServices =gatt.getServices();
BluetoothGattCharacteristic charData = bluetoothGatt.getService(SERVICE_UUID).getCharacteristic(DATA_UUID);
BluetoothGattCharacteristic charHeartbeat = bluetoothGatt.getService(SERVICE_UUID).getCharacteristic(HEARTBEAT_UUID);
//设置开启特性监听,这样onCharacteristicChanged才会有回调数据
bluetoothGatt.setCharacteristicNotification(charData, true);
bluetoothGatt.setCharacteristicNotification(charHeartbeat, true);
}
/// 特性变化时,收到通知
@Override
public void onCharacteristicChanged(
BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic
) {
super.onCharacteristicChanged(gatt, characteristic);
// 这里处理从BLE设备接收到的数据
byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
String receivedData = new String(data, StandardCharsets.UTF_8);
// 在主线程更新UI
runOnUiThread(() -> {
//parseAndDisplayData(receivedData);
});
}
}
};