Android BLE-读取特征数据-如何为按钮添加特征
我有一个班级活动。类的内部是UUID服务和特性的列表。单击UUID特性时,将读取有关特性的数据并显示 但我想用按钮替换列表。当我点击按钮时,它应该读取特征并显示出来。我的代码有问题:请帮助我 这是关于UUID列表的代码:Android BLE-读取特征数据-如何为按钮添加特征,android,bluetooth-lowenergy,android-bluetooth,Android,Bluetooth Lowenergy,Android Bluetooth,我有一个班级活动。类的内部是UUID服务和特性的列表。单击UUID特性时,将读取有关特性的数据并显示 但我想用按钮替换列表。当我点击按钮时,它应该读取特征并显示出来。我的代码有问题:请帮助我 这是关于UUID列表的代码: private final ExpandableListView.OnChildClickListener servicesListClickListner = new ExpandableListView.OnChildClickListener() {
private final ExpandableListView.OnChildClickListener servicesListClickListner = new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if (mGattCharacteristics != null) {
final BluetoothGattCharacteristic characteristic = mGattCharacteristics
.get(groupPosition).get(childPosition);
final int charaProp = characteristic.getProperties();
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
// If there is an active notification on a characteristic,
// clear
// it first so it doesn't update the data field on the user
// interface.
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(
mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
mBluetoothLeService.readCharacteristic(characteristic);
}
if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
mNotifyCharacteristic = characteristic;
mBluetoothLeService.setCharacteristicNotification(
characteristic, true);
}
return true;
}
return false;
}
};
这是按钮的代码:
mBattery.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final BluetoothGattCharacteristic characteristic = mGattCharacteristics
.get(4).get(1);
displayData(characteristic.getService().toString());
mBluetoothLeService.readCharacteristic(characteristic);
}
});
问题是当我单击按钮时:BLE已停止。
多谢各位 您应该检查logcat,以便可以从获得的异常中查看stacktrace。在不知道代码的其他部分是否有检查的情况下,很容易得到NullPointerException或ArrayIndexOutOfBoundsException,特别是因为您在mBattery.setOnClickListener中硬编码数组索引,即4和1 一般来说,您注册通知的方式不起作用,可能会导致问题。下面是一个如何操作的示例:
if( mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic, true) )
{
final UUID CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
BluetoothGattDescriptor descriptor = mNotifyCharacteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIGURATION_DESCRIPTOR_UUID);
if( descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) )
{
if( mBluetoothLeService.writeDescriptor(descriptor) )
{
// Now wait for callback to BluetoothGattCallback#onDescriptorWrite().
}
}
}