BLE Android 如何传递特征以在 Fragment 中使用
BLE Android how to pass characteristics to use in Fragment
我得到了一个 BLE 教程。我可以在 SPS 服务上发送和接收数据,此数据 TX RX 在 Dialog_BTLE_Characteristics 中完成。看起来特性和服务是使用以下命令从 Activity_BTLE_Services 传递到 Dialog_BTLE_Characteristic class。
Dialog_BTLE_Characteristic dialog_btle_characteristic = new Dialog_BTLE_Characteristic();
dialog_btle_characteristic.setTitle(uuid);
dialog_btle_characteristic.setService(mBTLE_Service);
dialog_btle_characteristic.setCharacteristic(characteristic);
然后在Dialog_BTLE_Characteristicclass中使用特性发送数据(输出):
characteristic.setValue(output);
service.writeCharacteristic(characteristic);
现在我想在 Fragment 中发送和接收数据。如何将这些特征和服务传递给 Fragment?
你的帮助会很大。
马里努斯
在片段中执行 BLE 操作是一种不好的做法。创建一个执行 BLE 操作的助手 class,并且仅将解码数据发送到 fragments/actvities 以供显示。
我认为如果您将代码分成不同的文件,您可能会有更好的时间移动。
我建议您将特征和设备 ID 传递给 fragment using a bundle:
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putString("someInt", someString);
myFragment.setArguments(args);
return myFragment;
}
//-------
// In the fragment
getArguments().getInt("someString");
几年来我一直在编写一些非常糟糕的代码,但它确实解决了很多繁重的工作:
//By the way, I think this is the server, better known as "Central Module", not the peripheral. I've had this misunderstanding until recently and still need to change the code
public class BLEPeripheral {
private String deviceId;
private BLEManager connector;
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeScanner bluetoothLeScanner;
private BluetoothGatt bluetoothGatt;
private BluetoothGattService bluetoothGattService = null;
private HashMap<String, Command<String>> subscriptions;
private boolean connected = false;
public boolean isConnected() {
return connected;
}
public BLEPeripheral(BLEManager connector, String deviceId) {
this.connector = connector;
this.deviceId = deviceId;
this.connector.onDisconnected();
final BluetoothManager bluetoothManager = (BluetoothManager) this.connector.getContext().getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
this.connector.enableBluetooth();
return;
}
if (!this.connector.checkPermission()) return;
scanForDevice();
}
public void scanForDevice() {
connected = false;
connector.log("BT ENABLED: SCANNING FOR DEVICES");
connector.reportState(BleManagerStatus.SEARCH_START);
bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
bluetoothLeScanner.startScan(mLEScanCallback);
}
public void stopScan() {
connector.reportState(BleManagerStatus.SCAN_CANCEL);
bluetoothLeScanner.stopScan(mLEScanCallback);
}
private final ScanCallback mLEScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
ScanRecord record = result.getScanRecord();
if (record == null) {
connector.log(String.format("Device [%s] has no scan record", device.getAddress()));
return;
}
String name = record.getDeviceName();
String UUID = null;
if (record.getServiceUuids() != null) {
for (ParcelUuid pId : record.getServiceUuids()) {
if (pId.getUuid().toString().equals(deviceId)) {
UUID = pId.getUuid().toString();
}
}
}
if (UUID == null) {
if (name != null) connector.log(String.format("Discovered Device [%s]. Continuing search", name));
return;
}
connector.log(String.format("Peripheral [%s] located on Device [%s]. Attempting connection", UUID, name));
bluetoothGatt = device.connectGatt(connector.getContext(), true, mGattCallback);
stopScan();
connector.reportState(BleManagerStatus.DEVICE_FOUND);
super.onScanResult(callbackType, result);
}
};
private void closeGatt() {
connector.reportState(BleManagerStatus.DICSONNECT);
connector.onDisconnected();
if (bluetoothGatt == null) {
return;
}
bluetoothGatt.close();
bluetoothGatt = null;
scanForDevice();
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
StringBuilder buffer;
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
connector.onConnectionStateChange(newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
connector.log("Connected to device GATT. Discovering services");
connector.reportState(BleManagerStatus.DEVICE_CONNECTED);
bluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
connector.log("Disconnected from GATT server. Continuing scanning");
closeGatt();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (bluetoothGatt.getServices() != null) {
connector.log("Services discovered: ["+bluetoothGatt.getServices().size()+"]");
for (BluetoothGattService service : bluetoothGatt.getServices()) {
if (service.getUuid().toString().equals(deviceId)) {
bluetoothGattService = service;
connector.onConnected();
connector.log("Service discovered");
connector.log("Attempting characteristic subscription");
connector.subscribeToCharacteristics();
}
}
}
} else {
connector.log(String.format("onServicesDiscovered received: [%s]", status));
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
connector.log(String.format("onCharacteristicRead received: [%s] value: [%s]", characteristic.getUuid().toString(), new String(characteristic.getValue())));
} else {
connector.log(String.format("onCharacteristicRead fail received: [%s]", status));
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
connector.log(String.format("onCharacteristicWrite received: [%s] value: [%s]", characteristic.getUuid().toString(), new String(characteristic.getValue())));
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
String packet = new String(characteristic.getValue());
if (packet.equals(String.valueOf((char)2))) {
buffer = new StringBuilder();
} else if (packet.equals(String.valueOf((char)3))) {
if (subscriptions == null || subscriptions.size() == 0) return;
Command<String> handler = subscriptions.get(characteristic.getUuid().toString());
if (handler != null) handler.execute(new String(buffer.toString()));
} else {
buffer.append(packet);
}
}
};
public BluetoothGattService getService() {
return bluetoothGattService;
}
private BluetoothGattCharacteristic findCharacteristicById(String id) {
if (bluetoothGattService.getCharacteristics() != null) {
return bluetoothGattService.getCharacteristic(java.util.UUID.fromString(id));
}
return null;
}
public void subscribe(String characteristicId, Command<String> handler){
if (subscriptions == null) subscriptions = new HashMap<>();
BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
if (characteristic == null) {
connector.log("Characteristic does not exist");
return;
}
connected = true;
connector.reportState(BleManagerStatus.CHARACTERISTIC_SUBSCRIBED);
bluetoothGatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
bluetoothGatt.writeDescriptor(descriptor);
subscriptions.put(characteristicId, handler);
}
public void writeCharacteristic(String characteristicId, String data) {
BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
if (characteristic != null) {
characteristic.setValue(data);
bluetoothGatt.writeCharacteristic(characteristic);
connector.log(String.format("Wrote [%s] to [%s]", data, characteristicId));
} else {
connector.log(String.format("[%s] not found on device", characteristicId));
}
}
public void readCharacteristic(String characteristicId) {
BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
if (characteristic == null) return;
bluetoothGatt.readCharacteristic(characteristic);
}
}
那我只需要传一个BLEManager
的实例进去,就是一个简单的接口:
public interface BLEManager {
void log(String message);
void reportState(BleManagerStatus status);
void onConnectionStateChange(int newState);
Context getContext();
void enableBluetooth();
void onConnected();
void subscribeToCharacteristics();
void onDisconnected();
boolean checkPermission();
}
而您的片段/activity 可以实现它。我认为这称为 adapter pattern,因为我将 BLE 的实现从 Android 生命周期中抽象出来。
我得到了一个 BLE 教程。我可以在 SPS 服务上发送和接收数据,此数据 TX RX 在 Dialog_BTLE_Characteristics 中完成。看起来特性和服务是使用以下命令从 Activity_BTLE_Services 传递到 Dialog_BTLE_Characteristic class。
Dialog_BTLE_Characteristic dialog_btle_characteristic = new Dialog_BTLE_Characteristic();
dialog_btle_characteristic.setTitle(uuid);
dialog_btle_characteristic.setService(mBTLE_Service);
dialog_btle_characteristic.setCharacteristic(characteristic);
然后在Dialog_BTLE_Characteristicclass中使用特性发送数据(输出):
characteristic.setValue(output);
service.writeCharacteristic(characteristic);
现在我想在 Fragment 中发送和接收数据。如何将这些特征和服务传递给 Fragment?
你的帮助会很大。 马里努斯
在片段中执行 BLE 操作是一种不好的做法。创建一个执行 BLE 操作的助手 class,并且仅将解码数据发送到 fragments/actvities 以供显示。
我认为如果您将代码分成不同的文件,您可能会有更好的时间移动。
我建议您将特征和设备 ID 传递给 fragment using a bundle:
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putString("someInt", someString);
myFragment.setArguments(args);
return myFragment;
}
//-------
// In the fragment
getArguments().getInt("someString");
几年来我一直在编写一些非常糟糕的代码,但它确实解决了很多繁重的工作:
//By the way, I think this is the server, better known as "Central Module", not the peripheral. I've had this misunderstanding until recently and still need to change the code
public class BLEPeripheral {
private String deviceId;
private BLEManager connector;
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeScanner bluetoothLeScanner;
private BluetoothGatt bluetoothGatt;
private BluetoothGattService bluetoothGattService = null;
private HashMap<String, Command<String>> subscriptions;
private boolean connected = false;
public boolean isConnected() {
return connected;
}
public BLEPeripheral(BLEManager connector, String deviceId) {
this.connector = connector;
this.deviceId = deviceId;
this.connector.onDisconnected();
final BluetoothManager bluetoothManager = (BluetoothManager) this.connector.getContext().getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
this.connector.enableBluetooth();
return;
}
if (!this.connector.checkPermission()) return;
scanForDevice();
}
public void scanForDevice() {
connected = false;
connector.log("BT ENABLED: SCANNING FOR DEVICES");
connector.reportState(BleManagerStatus.SEARCH_START);
bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
bluetoothLeScanner.startScan(mLEScanCallback);
}
public void stopScan() {
connector.reportState(BleManagerStatus.SCAN_CANCEL);
bluetoothLeScanner.stopScan(mLEScanCallback);
}
private final ScanCallback mLEScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
BluetoothDevice device = result.getDevice();
ScanRecord record = result.getScanRecord();
if (record == null) {
connector.log(String.format("Device [%s] has no scan record", device.getAddress()));
return;
}
String name = record.getDeviceName();
String UUID = null;
if (record.getServiceUuids() != null) {
for (ParcelUuid pId : record.getServiceUuids()) {
if (pId.getUuid().toString().equals(deviceId)) {
UUID = pId.getUuid().toString();
}
}
}
if (UUID == null) {
if (name != null) connector.log(String.format("Discovered Device [%s]. Continuing search", name));
return;
}
connector.log(String.format("Peripheral [%s] located on Device [%s]. Attempting connection", UUID, name));
bluetoothGatt = device.connectGatt(connector.getContext(), true, mGattCallback);
stopScan();
connector.reportState(BleManagerStatus.DEVICE_FOUND);
super.onScanResult(callbackType, result);
}
};
private void closeGatt() {
connector.reportState(BleManagerStatus.DICSONNECT);
connector.onDisconnected();
if (bluetoothGatt == null) {
return;
}
bluetoothGatt.close();
bluetoothGatt = null;
scanForDevice();
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
StringBuilder buffer;
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
connector.onConnectionStateChange(newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
connector.log("Connected to device GATT. Discovering services");
connector.reportState(BleManagerStatus.DEVICE_CONNECTED);
bluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
connector.log("Disconnected from GATT server. Continuing scanning");
closeGatt();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (bluetoothGatt.getServices() != null) {
connector.log("Services discovered: ["+bluetoothGatt.getServices().size()+"]");
for (BluetoothGattService service : bluetoothGatt.getServices()) {
if (service.getUuid().toString().equals(deviceId)) {
bluetoothGattService = service;
connector.onConnected();
connector.log("Service discovered");
connector.log("Attempting characteristic subscription");
connector.subscribeToCharacteristics();
}
}
}
} else {
connector.log(String.format("onServicesDiscovered received: [%s]", status));
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
connector.log(String.format("onCharacteristicRead received: [%s] value: [%s]", characteristic.getUuid().toString(), new String(characteristic.getValue())));
} else {
connector.log(String.format("onCharacteristicRead fail received: [%s]", status));
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
connector.log(String.format("onCharacteristicWrite received: [%s] value: [%s]", characteristic.getUuid().toString(), new String(characteristic.getValue())));
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
String packet = new String(characteristic.getValue());
if (packet.equals(String.valueOf((char)2))) {
buffer = new StringBuilder();
} else if (packet.equals(String.valueOf((char)3))) {
if (subscriptions == null || subscriptions.size() == 0) return;
Command<String> handler = subscriptions.get(characteristic.getUuid().toString());
if (handler != null) handler.execute(new String(buffer.toString()));
} else {
buffer.append(packet);
}
}
};
public BluetoothGattService getService() {
return bluetoothGattService;
}
private BluetoothGattCharacteristic findCharacteristicById(String id) {
if (bluetoothGattService.getCharacteristics() != null) {
return bluetoothGattService.getCharacteristic(java.util.UUID.fromString(id));
}
return null;
}
public void subscribe(String characteristicId, Command<String> handler){
if (subscriptions == null) subscriptions = new HashMap<>();
BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
if (characteristic == null) {
connector.log("Characteristic does not exist");
return;
}
connected = true;
connector.reportState(BleManagerStatus.CHARACTERISTIC_SUBSCRIBED);
bluetoothGatt.setCharacteristicNotification(characteristic, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
bluetoothGatt.writeDescriptor(descriptor);
subscriptions.put(characteristicId, handler);
}
public void writeCharacteristic(String characteristicId, String data) {
BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
if (characteristic != null) {
characteristic.setValue(data);
bluetoothGatt.writeCharacteristic(characteristic);
connector.log(String.format("Wrote [%s] to [%s]", data, characteristicId));
} else {
connector.log(String.format("[%s] not found on device", characteristicId));
}
}
public void readCharacteristic(String characteristicId) {
BluetoothGattCharacteristic characteristic = findCharacteristicById(characteristicId);
if (characteristic == null) return;
bluetoothGatt.readCharacteristic(characteristic);
}
}
那我只需要传一个BLEManager
的实例进去,就是一个简单的接口:
public interface BLEManager {
void log(String message);
void reportState(BleManagerStatus status);
void onConnectionStateChange(int newState);
Context getContext();
void enableBluetooth();
void onConnected();
void subscribeToCharacteristics();
void onDisconnected();
boolean checkPermission();
}
而您的片段/activity 可以实现它。我认为这称为 adapter pattern,因为我将 BLE 的实现从 Android 生命周期中抽象出来。