| | |
| | | |
| | | if (bluetoothGatt != null) { |
| | | bluetoothGatt.disconnect(); // 先断开连接 |
| | | bluetoothGatt.close(); |
| | | bluetoothGatt = null; |
| | | // bluetoothGatt.close(); |
| | | // bluetoothGatt = null; |
| | | Log.d(TAG, "Connecting to 先断开旧蓝牙连接"); |
| | | } |
| | | BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress); |
| | | // 自动连接 = false,避免系统缓存连接 |
| | |
| | | gatt.discoverServices(); |
| | | } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { |
| | | isConnected = false; |
| | | if (bluetoothGatt != null) { |
| | | bluetoothGatt.close(); |
| | | bluetoothGatt = null; |
| | | } |
| | | if (connectListener != null) { |
| | | callbackHandler.post(() -> connectListener.onDisconnected()); |
| | | } |
| | | |
| | | Log.d(TAG, "Connected to GATT server, onDisconnected"); |
| | | }// |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | } |
| | | |
| | | @Override |
| | | public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) { |
| | | //todo 后面兼用mtc分包的,目前默认设置512字节 |
| | |
| | | // 第 4 步:写入描述符到设备 |
| | | //↑ 只有写入成功后,告诉设备端,设备才会开始发送通知, |
| | | bluetoothGatt.writeDescriptor(descriptor); |
| | | Log.e(TAG, "writeDescriptor success"); |
| | | Log.d(TAG, "writeDescriptor success"); |
| | | } |
| | | } |
| | | } |
| | |
| | | */ |
| | | @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) |
| | | public void writeCredentials(String data, WriteListener listener) { |
| | | Log.e(TAG, "writeCredentials :准备写入"); |
| | | Log.d(TAG, "writeCredentials :准备写入"); |
| | | this.writeListener = listener; |
| | | if (!isConnected || characteristic == null) { |
| | | if (listener != null) { |
| | |
| | | |
| | | @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT) |
| | | private void writeCharacteristic(BluetoothGattCharacteristic characteristic, String value) { |
| | | Log.e(TAG, "writeCharacteristic :开始写入"); |
| | | Log.d(TAG, "writeCharacteristic :开始写入"); |
| | | if (!this.getMissingPermissions().isEmpty()) { |
| | | callbackHandler.post(() -> this.writeListener.onWriteFailed(-2)); // 没有权限 |
| | | return; |
| | |
| | | characteristic.setValue(value.getBytes(StandardCharsets.UTF_8)); |
| | | characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); |
| | | bluetoothGatt.writeCharacteristic(characteristic); |
| | | Log.e(TAG, "writeCharacteristic :开始完成"); |
| | | Log.d(TAG, "writeCharacteristic :开始完成"); |
| | | } |
| | | |
| | | // ==================== 工具方法 ==================== |