Android 4.3 Bluetooth не вызывает onCharacteristicRead ()

Я установил уведомление в android, оно не вызывает метод _1 _ ???? В функцию не входит. Почему так происходит ??

Любая помощь приветствуется

Запросите решения.

Это мой код:

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
            int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            Log.i(TAG, "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            Log.i(TAG, "Attempting to start service discovery:"
                    + mBluetoothGatt.discoverServices());
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            Log.i(TAG, "Disconnected from GATT server.");
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            gattServices = mBluetoothGatt
                    .getService(SampleGattAttributes.SERVICES_UUID);
            if (gattServices != null) {
                gattCharacteristics = gattServices
                        .getCharacteristic(SampleGattAttributes.CHARACTERISTIC_UUID);
                System.out.println("character-->" + gattCharacteristics);
            }
            if (gattCharacteristics != null) {
                System.out.println("Characteristic not null");
                System.out.println("Characteristic Properties-->"
                        + gattCharacteristics.getProperties());
                mBluetoothGatt.setCharacteristicNotification(gattCharacteristics,
                true);
            }
        } else {
            Log.w(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic, int status) {
        System.out.println("in read");
        if (status == BluetoothGatt.GATT_SUCCESS) {
            byte[] data = characteristic.getValue();
            System.out.println("reading");
            System.out.println(new String(data));
        }
    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
            BluetoothGattCharacteristic characteristic) {
        //
        System.out.println("change");
        byte[] data = characteristic.getValue();
        System.out.println(new String(data));
    }
};

Заранее спасибо!!


person Jianping Zhu    schedule 16.09.2014    source источник


Ответы (1)


Прежде всего onCharacteristicRead будет срабатывать, если вы прочитали характеристику:

 mBluetoothGatt.readCharacteristic(characteristic);

Считывание характеристики и настройка уведомлений - разные вещи. По какому типу характеристики вы хотите получить данные?

Is it:

  • читать
  • поставить в известность
  • указывать

Если это read, вы можете прочитать характеристику, используя метод mBluetoothGatt.readCharacteristic(characteristic);, но если это notify или indicate, сначала вам нужно будет прочитать descriptor характеристики, вызвав:

mBluetoothGatt.readDescriptor(ccc);

После того, как вы его прочтете, он должен вернуть данные, вызвав обратный вызов onDescriptorRead.
Здесь вы можете настроить (подписаться) на characteritic посредством уведомления или индикации, вызвав:

mBluetoothGatt.setCharacteristicNotification(characteristic, true)

как только он вернет true, вам нужно будет снова записать в дескриптор (значение уведомления или индикации)

BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(CCC);
clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
// or
//clientConfig.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
mBluetoothGatt.writeDescriptor(clientConfig);

Как только это будет сделано, вы будете получать уведомления через onCharacteristicChanged обратный вызов каждый раз при изменении характеристики.

вы можете узнать больше о соединении Bluetooth на Android здесь
и о характеристиках Bluetooth здесь

person benka    schedule 16.09.2014
comment
Спасибо за ответ. Я потерял дескриптор и установил неправильный uuid, поэтому дескриптор имеет значение null, он не выполняет clientConfig.setValue (BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); - person Jianping Zhu; 17.09.2014
comment
Привет, Бенка, я столкнулся с проблемой во время операции чтения и записи, ты мне поможешь. - person chet's; 11.12.2014
comment
@ chet's - опубликуйте ссылку на свой вопрос и позвольте мне посмотреть, могу ли я что-нибудь для вас сделать. - person benka; 11.12.2014
comment
@benka, пожалуйста, проверьте мой вопрос на stackoverflow.com/questions/27443139/ - person chet's; 12.12.2014