智能穿戴中,想要获得数据,首先需要连接上设备的蓝牙才行,下边介绍一种连接设备的方法。
NormalText Code
// 搜索设备并添加到列表中
public Boolean SearchToList() {// 打开蓝牙,搜索设备
if (bluetoothAdapter != null) {
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
// 打开蓝牙
bluetoothAdapter.enable();
log.E("打开蓝牙!");
// 搜索设备
bluetoothAdapter.startLeScan(scanCallback);
log.E("开始搜索!");
return true;
} else {
// 搜索设备
bluetoothAdapter.startLeScan(scanCallback);
log.E("开始搜索!");
return true;
}
} else {
log.E("bluetoothAdapter == null");
return false;
}
}
private BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback()
@Override
public void onLeScan(final BluetoothDevice device, int rssi,byte[] scanRecord) {
if ((device != null) && (deviceList != null)) {
if ((Isrepeat(device, deviceList) == false)&& (device.getName() != null)) {
deviceList.add(device);
deviceName.add(device.getName());
deviceAddr.add(device.getAddress());
}
}
}
};
连接上设备以后,还需要获得设备的相关信息。
NormalText Code
// 连接设备并获得特征值
public synchronized boolean BLEConnect(BluetoothDevice remoteDev) {
if (remoteDev == null) {
return false;
}
bluetoothGatt = remoteDev.connectGatt(context, false, gattCallback);
return true;
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {
if (bluetoothGatt != null) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
log.E("连接成功!");
handler.sendEmptyMessage(3);
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
log.E("连接断开!");
handler.sendEmptyMessage(4);
}
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (gatt != null) {
bluetoothService = gatt.getService(UUID.fromString(serviceUUID));
if (bluetoothService != null) {
characteristic = bluetoothService.getCharacteristic(UUID.fromString(characteristicUUID));
if (characteristic != null) {
bluetoothGatt.setCharacteristicNotification(characteristic, true);
// bluetoothGatt.readCharacteristic(characteristic);
} else {
log.E("characteristic == null");
}
} else {
log.E("bluetoothService == null");
}
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {
// log.E("onCharacteristicChanged");
readDate = characteristic.getValue();
if ((readDate != null) && (readDate.length > 0)) {
handler.sendEmptyMessage(1);
handler.sendEmptyMessage(2);
} else {
log.E("接收数据失败!");
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
log.E("onCharacteristicWrite" + "-" + status);
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic, int status) {
log.E("onCharacteristicRead" + "-" + status);
}
}
Copyright © 2004-2024 华清远见教育科技集团 版权所有
京ICP备16055225号-5,京公海网安备11010802025203号