代码如下:
public void readBattery() {
Log.d("demo", "readBattery");
BluetoothGattService batteryService = mBluetoothGatt.getService(UUID.fromString(BATTERY_SERVICE));
BluetoothGattCharacteristic batteryCharacteristic = batteryService.getCharacteristic(UUID.fromString(BATTERY_CHARATERISTIC));
if (batteryCharacteristic != null) {
readCharacteristic(batteryCharacteristic);
}
}
}
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothGatt == null || mBluetoothAdapter == null) {
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
回调的代码:
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_BATTERY, characteristic);
}
广播代码:
private void broadcastUpdate(String action, BluetoothGattCharacteristic characteristic) {
final Intent intent = new Intent(action);
String uuid = characteristic.getUuid().toString();
if (uuid.equalsIgnoreCase(BATTERY_CHARATERISTIC)) {
byte[] databattery = characteristic.getValue();
analysisData(intent,databattery);
}
数据解析
public void analysisData(Intent intent, byte[] data) {
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for (byte byteChar : data)
stringBuilder.append(String.format("%02X", byteChar));
String builder = stringBuilder.toString();
Log.d("demo", "0x -->" + builder); //一直显示64,十六进制,十进制100
intent.putExtra(EXTRA_DATA,builder);
sendBroadcast(intent);
}
}
求大牛帮忙看看哪里不对,为什么电量一直显示100不变化