2条回答
- leeisshe 2019-11-08 14:03关注
不能接受数据是因为权限没给
在回调里面重写onServicesDiscovered
@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { super.onServicesDiscovered(gatt, status); Log.e(TAG, "onServicesDiscovered gatt = " + gatt); if (status == BluetoothGatt.GATT_SUCCESS) { String address = gatt.getDevice().getAddress(); threadSleep(200); displayGattServices(gatt, address); } } //发现所连接设备的服务和特征
对所有的特征都付给权限,肯定能行(我这里是对特征的uuid做了过滤,你不知道UUID的情况下可以不过滤,对所有的特征都赋权限)
private void displayGattServices(BluetoothGatt gatt, String address) { List<BluetoothGattService> gattServices = getSupportedGattServices(gatt); if (gattServices == null) return; String uuid = null; for (BluetoothGattService gattService : gattServices) { // 列表中有(gattServices) gattServices 此处遍历每一个gattService 找到单片机的通知特征 打开通知(后续就可以自动接到消息) uuid = gattService.getUuid().toString(); Log.e(TAG, "displayGattServices uuid = " + uuid); if (uuid.equals(SERVICE_UUID)) { mReadCharacteristic = gattService.getCharacteristic(UUID.fromString(NOTIFICATION_UUID)); mWriteCharacteristic = gattService.getCharacteristic(UUID.fromString(WRITE_UUID)); } } if (mReadCharacteristic != null) { final int charaProp = mReadCharacteristic.getProperties(); if ((charaProp | BluetoothGattCharacteristic.PROPERTY_READ) > 0) { Log.e(TAG, "displayGattServices PROPERTY_READ > 0 "); readCharacteristic(gatt, mReadCharacteristic); } threadSleep(1000); if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { Log.e(TAG, "displayGattServices PROPERTY_NOTIFY > 0 "); setCharacteristicNotification(gatt, mReadCharacteristic, true); } } else { Log.w(TAG, "unable to find NOTIFICATION_UUID"); } }
赋权限方法如下
public void readCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { if (gatt == null || mBluetoothAdapter == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } gatt.readCharacteristic(characteristic); } public void setCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, boolean enable) { if (gatt == null || mBluetoothAdapter == null) { Log.w(TAG, "BluetoothAdapter not initialized"); return; } gatt.setCharacteristicNotification(characteristic, enable); BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(CLIENT_CHARACTERISTIC_CONFIG)); descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); gatt.writeDescriptor(descriptor); }
解决 1无用
悬赏问题
- ¥15 多电路系统共用电源的串扰问题
- ¥15 shape_predictor_68_face_landmarks.dat
- ¥15 slam rangenet++配置
- ¥15 有没有研究水声通信方面的帮我改俩matlab代码
- ¥15 对于相关问题的求解与代码
- ¥15 ubuntu子系统密码忘记
- ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
- ¥15 保护模式-系统加载-段寄存器
- ¥15 电脑桌面设定一个区域禁止鼠标操作
- ¥15 求NPF226060磁芯的详细资料