BluetoothGatt:特征读取后断开连接

时间:2016-12-24 10:53:30

标签: android bluetooth bluetooth-lowenergy

我正在尝试从BLE设备读取/写入值。这是我的代码:

...
private BluetoothAdapter mBluetoothAdapter;
private int REQUEST_ENABLE_BT = 1;
private Handler mHandler;
private static final long SCAN_PERIOD = 10000;
private BluetoothLeScanner mLEScanner;
private ScanSettings settings;
private List<ScanFilter> filters;
private List<BluetoothGattService> services;
private BluetoothGatt mGatt;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private byte BYTE_STAG = 0;
private byte BYTE_SPHONE = 0;
...
    @Override
protected void onResume() {
    final Handler h = new Handler();
    final int delay = 10000; //milliseconds

    h.postDelayed(new Runnable(){
        public void run(){

            Handler handler1 = new Handler();
            handler1.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "notifications!", Toast.LENGTH_LONG).show();
                    readSensorTagNotificationValue();
                }
            }, 5000);
            Handler handler2 = new Handler();
            handler2.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "time!", Toast.LENGTH_LONG).show();
                    syncClock();
                }
            }, 10000);

            h.postDelayed(this, delay);
        }
    }, delay);

    super.onResume();
}
...

syncClock()将byte []值发送到特定的设备特性,并且它可以正常工作。 我的问题是在readSensorTagNotificationValue()方法中,我必须阅读一个特征。方法是:

    private void readSensorTagNotificationValue() {
    // Discover service characteristic
    List<BluetoothGattCharacteristic> characteristics = (services.get(8).getCharacteristics());
    Log.i("CHARACTER SIZE", String.valueOf(characteristics.size()));
    BluetoothGattCharacteristic ch = characteristics.get(1);
    Log.i("CHARACTER PROP", String.valueOf(ch.getUuid()));

    // Read SensorTag notification value
    mGatt.readCharacteristic(ch);
    Log.i("CH READ", "test");
    byte[] readValue = ch.getValue();
    if (readValue == null) {
        Toast.makeText(getApplicationContext(), "null value read", Toast.LENGTH_LONG).show();
        return;
    }
    BYTE_STAG = readValue[0];
    Log.i("BYTE_STAG", String.valueOf(BYTE_STAG));
}

问题是,在阅读程序后,智能手机会断开与BLE设备的连接。 Android Monitor输出如下:

I/CHARACTER SIZE: 2
I/CHARACTER PROP: f000ad02-0451-4000-b000-000000000000
I/CH READ: test
I/onCharacteristicRead: android.bluetooth.BluetoothGattCharacteristic@8e46463
D/BluetoothGatt: cancelOpen() - device: 24:71:89:BE:CF:07
D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=8 device=24:71:89:BE:CF:07
I/onConnectionStateChange: Status: 0
E/gattCallback: STATE_DISCONNECTED

0 个答案:

没有答案