Android BLE连接

时间:2016-08-03 11:42:57

标签: android bluetooth-lowenergy android-bluetooth

我是Android蓝牙API新手。我必须将我的应用程序与血压计连接并获取测量数据。当设备未与我的手机配对时,我设法使连接正常工作并获取数据。但是,当它配对时,我会在status = 8中获得onConnectionChanged。这是我的代码

这是我的mGattCallback

 private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
        DebugLogger.debug("Status is "+status+" - new state is "+newState);

        if (status == BluetoothGatt.GATT_SUCCESS) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                mCallbacks.onDeviceConnected();
                // start discovering services
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                mCallbacks.onDeviceDisconnected();
                gatt.close();
            }
        } else {
            mCallbacks.onError(ERROR_CONNECTION_STATE_CHANGE, status);
        }
    }

此处我连接或断开设备

 @Override
public void connect(final Context context, final BluetoothDevice device) {
    mBluetoothGatt = device.connectGatt(context, true, mGattCallback);
    mContext = context;
}

@Override
public void disconnect() {
    if (mBluetoothGatt != null) {
        mBluetoothGatt.disconnect();
    }
}

这是用于在设备断开连接后关闭整个连接

 @Override
public void closeBluetoothGatt() {
    try {
        mContext.unregisterReceiver(mBondingBroadcastReceiver);
    } catch (Exception e) {
        // the receiver must have been not registered or unregistered before
    }

    if (mBluetoothGatt != null) {
        mBluetoothGatt.close();
        mBPMCharacteristic = null;
        mBatteryCharacteristic = null;
        mBluetoothGatt = null;
    }
}

我知道状态8表示我的连接超时。我错过了什么吗?因为只有当我尝试连接到配对设备时才会这样做才真的很奇怪

0 个答案:

没有答案