安卓中實現藍牙通信的工具
時間:2018-09-21 來源:未知
智能穿戴中,想要獲得數據,首先需要連接上設備的藍牙才行,下邊介紹一種連接設備的方法。
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);
}
}

