引入蓝牙依赖
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
package com.ckkj.water.utils.manager;
|
||||
|
||||
import android.bluetooth.BluetoothGatt;
|
||||
import android.bluetooth.BluetoothGattCharacteristic;
|
||||
import android.bluetooth.BluetoothGattService;
|
||||
import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.UUID;
|
||||
|
||||
import no.nordicsemi.android.ble.BleManager;
|
||||
|
||||
/**
|
||||
* @author fengxiaoyang
|
||||
* @date 2026/6/3
|
||||
* @description 蓝牙设备管理
|
||||
*/
|
||||
public class WaterDeviceManager extends BleManager {
|
||||
private BluetoothGattCharacteristic writeCharacteristic;
|
||||
private BluetoothGattCharacteristic notifyCharacteristic;
|
||||
|
||||
public WaterDeviceManager(@NonNull Context context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
protected BleManagerGattCallback getGattCallback() {
|
||||
return new DeviceGattCallback();
|
||||
}
|
||||
|
||||
private class DeviceGattCallback extends BleManagerGattCallback {
|
||||
|
||||
@Override
|
||||
protected void initialize() {
|
||||
|
||||
setNotificationCallback(notifyCharacteristic)
|
||||
.with((device, data) -> {
|
||||
|
||||
byte[] bytes = data.getValue();
|
||||
|
||||
Log.e("TEST", "收到数据: "
|
||||
+ Arrays.toString(bytes));
|
||||
});
|
||||
|
||||
enableNotifications(notifyCharacteristic)
|
||||
.enqueue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isRequiredServiceSupported(@NonNull BluetoothGatt gatt) {
|
||||
|
||||
BluetoothGattService service =
|
||||
gatt.getService(UUID.fromString(
|
||||
"0000ffff-0000-1000-8000-00805f9b34fb"));
|
||||
|
||||
if (service == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
writeCharacteristic =
|
||||
service.getCharacteristic(UUID.fromString(
|
||||
"0000ff01-0000-1000-8000-00805f9b34fb"));
|
||||
|
||||
notifyCharacteristic =
|
||||
service.getCharacteristic(UUID.fromString(
|
||||
"0000ff02-0000-1000-8000-00805f9b34fb"));
|
||||
|
||||
return writeCharacteristic != null
|
||||
&& notifyCharacteristic != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onServicesInvalidated() {
|
||||
writeCharacteristic = null;
|
||||
notifyCharacteristic = null;
|
||||
}
|
||||
}
|
||||
|
||||
public void send(byte[] data) {
|
||||
|
||||
if (writeCharacteristic == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
writeCharacteristic(writeCharacteristic, data)
|
||||
.enqueue();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user