Example usage for android.bluetooth BluetoothGatt close

List of usage examples for android.bluetooth BluetoothGatt close

Introduction

In this page you can find the example usage for android.bluetooth BluetoothGatt close.

Prototype

public void close() 

Source Link

Document

Close this Bluetooth GATT client.

Usage

From source file:ble.AndroidBle.java

@Override
public void disconnect(String address) {
    if (mBluetoothGatts.containsKey(address)) {
        BluetoothGatt gatt = mBluetoothGatts.remove(address);
        if (gatt != null) {
            gatt.disconnect();// w w  w .  j av  a  2s  .  co m
            gatt.close();
        }
    }
}

From source file:com.wolkabout.hexiwear.service.BluetoothService.java

private void handleAuthenticationError(final BluetoothGatt gatt) {
    gatt.close();
    sendBroadcast(new Intent(BluetoothService.ACTION_NEEDS_BOND));
    gatt.getDevice().createBond();/*from ww  w .j  av a  2s . c  o  m*/
}

From source file:com.google.android.apps.forscience.ble.MyBleService.java

void resetGatt() {
    if (btAdapter != null && isScanning) {
        btAdapter.stopLeScan(scanCallback);
    }// www  .j a  v  a 2 s .  com
    for (BluetoothGatt bluetoothGatt : addressToGattClient.values()) {
        bluetoothGatt.close();
    }
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeGattPeripheral.java

private void handleGattDisconnect(@Nullable BluetoothGatt gatt) {
    if (gatt != null) {
        logger.info(LOG_TAG, "Closing gatt layer");

        gatt.close();
        if (gatt == this.gatt) {
            logger.info(GattPeripheral.LOG_TAG, "dispatchDisconnect()");

            gattDispatcher.clearListeners();

            for (final Runnable onDisconnect : disconnectListeners) {
                onDisconnect.run();//from  w ww  . j  a  v a 2 s.  c  om
            }
            disconnectListeners.clear();

            for (final NativeGattService service : services.values()) {
                service.dispatchDisconnect();
            }

            this.gatt = null;
            this.services = Collections.emptyMap();

            stopObservingBluetoothState();
        }
    }
}

From source file:com.google.android.apps.forscience.ble.MyBleService.java

public void disconnectDevice(String address) {
    BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
    if (btAdapter == null || address == null || bluetoothGatt == null) {
        return;//from   ww w .j  a  v  a2s  .  c  o  m
    }
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    int bleState = bluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    if (bleState != BluetoothProfile.STATE_DISCONNECTED && bleState != BluetoothProfile.STATE_DISCONNECTING) {
        bluetoothGatt.disconnect();
    } else {
        bluetoothGatt.close();
        addressToGattClient.remove(address);
        sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
    }
}

From source file:com.google.android.apps.forscience.ble.MyBleService.java

boolean connect(String address) {
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    if (device == null) {
        return false;
    }/*w  w  w .  ja v  a 2  s. com*/
    BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
    int connectionState = bluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    if (bluetoothGatt != null && connectionState != BluetoothProfile.STATE_CONNECTED) {
        return bluetoothGatt.connect();
    }
    if (bluetoothGatt != null && connectionState == BluetoothProfile.STATE_CONNECTED) {
        sendGattBroadcast(address, BleEvents.GATT_CONNECT, null);
        return true;
    }

    if (bluetoothGatt != null) {
        bluetoothGatt.close();
    }
    bluetoothGatt = device.connectGatt(this, false, // autoConnect = false
            gattCallbacks);
    addressToGattClient.put(address, bluetoothGatt);
    return true;
}

From source file:com.nbplus.iotapp.bluetooth.BluetoothLeService.java

public void close(String address) {
    if (StringUtils.isEmptyString(address)) {
        Log.w(TAG, "Unknown address");
    }//from w w  w  .  j  a  v a  2 s  .c  om
    BluetoothGatt bluetoothGatt = mConnectedBluetoothGattMap.get(address);
    if (bluetoothGatt == null) {
        return;
    }
    Log.d(TAG, "close ble gatt resources !!");
    bluetoothGatt.close();
    mConnectedBluetoothGattMap.remove(address);
}

From source file:no.nordicsemi.android.nrftoolbox.dfu.DfuService.java

/**
 * Closes the GATT device and cleans up.
 * // ww w  .  ja  v  a  2 s . c  om
 * @param gatt
 *            the GATT device to be closed
 */
private void close(final BluetoothGatt gatt) {
    logi("Cleaning up...");
    gatt.close();
    mConnectionState = STATE_CLOSED;
}

From source file:net.emilymaier.movebot.HeartFragment.java

@Override
@SuppressWarnings("deprecation")
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
    Log.d("HeartFragment", "Bluetooth LE device found");
    BluetoothGatt bluetoothGatt = device.connectGatt(act, false, new BluetoothGattCallback() {
        @Override/*from   w  ww . ja  v  a2  s.c  o  m*/
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.d("HeartFragment", "Connected to LE device");
                gatt.discoverServices();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                BluetoothGattCharacteristic characteristic = null;
                for (BluetoothGattService service : gatt.getServices()) {
                    characteristic = service
                            .getCharacteristic(UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb"));
                    if (characteristic != null) {
                        break;
                    }
                }
                if (characteristic != null) {
                    Log.d("HeartFragment", "Found device with HRM characteristic");
                    HeartDevice device = new HeartDevice();
                    device.bluetoothGatt = gatt;
                    device.characteristic = characteristic;
                    for (HeartDevice testDevice : heartDevices) {
                        if (testDevice.bluetoothGatt.getDevice().getAddress()
                                .equals(device.bluetoothGatt.getDevice().getAddress())) {
                            heartDevices.remove(testDevice);
                        }
                    }
                    heartDevices.add(device);
                } else {
                    Log.d("HeartFragment", "Device does not have HRM characteristic");
                    gatt.disconnect();
                    gatt.close();
                }
            } else {
                Log.w("HeartFragment", "Failed to discover device services");
                gatt.disconnect();
                gatt.close();
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            int flag = characteristic.getProperties();
            int format = -1;
            if ((flag & 0x01) != 0) {
                format = BluetoothGattCharacteristic.FORMAT_UINT16;
            } else {
                format = BluetoothGattCharacteristic.FORMAT_UINT8;
            }
            final int heartRate = characteristic.getIntValue(format, 1);
            act.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    act.updateHeart(heartRate);
                }
            });
        }
    });
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeGattPeripheral.java

@NonNull
@Override//from w  w w .j a va  2 s  .c o  m
@RequiresPermission(Manifest.permission.BLUETOOTH)
public Observable<GattPeripheral> connect(@ConnectFlags final int flags,
        @NonNull final OperationTimeout timeout) {
    return createObservable(new Observable.OnSubscribe<GattPeripheral>() {
        @Override
        public void call(final Subscriber<? super GattPeripheral> subscriber) {
            if (getConnectionStatus() == STATUS_CONNECTED) {
                logger.warn(LOG_TAG, "Redundant call to connect(), ignoring.");

                subscriber.onNext(NativeGattPeripheral.this);
                subscriber.onCompleted();
                return;
            } else if (getConnectionStatus() == STATUS_CONNECTING
                    || getConnectionStatus() == STATUS_DISCONNECTING) {
                subscriber.onError(new ConnectionStateException("Peripheral is changing connection status."));
                return;
            }

            final boolean autoConnect = ((flags & CONNECT_FLAG_WAIT_AVAILABLE) == CONNECT_FLAG_WAIT_AVAILABLE);
            final int transport = getTransportFromConnectFlags(flags);

            final GattDispatcher.ConnectionListener listener = new GattDispatcher.ConnectionListener() {
                boolean hasRetried = false;

                @Override
                boolean onConnected(@NonNull final BluetoothGatt gatt, int status) {
                    timeout.unschedule();

                    logger.info(LOG_TAG, "Connected " + NativeGattPeripheral.this.toString());

                    startObservingBluetoothState();

                    disconnectForwarder.setEnabled(true);
                    subscriber.onNext(NativeGattPeripheral.this);
                    subscriber.onCompleted();

                    final Intent connectedIntent = new Intent(ACTION_CONNECTED).putExtra(EXTRA_NAME, getName())
                            .putExtra(EXTRA_ADDRESS, getAddress());
                    LocalBroadcastManager.getInstance(stack.applicationContext).sendBroadcast(connectedIntent);

                    return false;
                }

                @Override
                boolean onError(@NonNull BluetoothGatt gatt, int status, int state) {
                    // The first connection attempt made after a user has power cycled their radio,
                    // or the connection to a device is unexpectedly lost, will seemingly fail 100%
                    // of the time. The error code varies by manufacturer. Retrying silently resolves
                    // the issue.
                    if (GattException.isRecoverableConnectError(status) && !hasRetried) {
                        logger.warn(LOG_TAG, "First connection attempt failed due to stack error, retrying.");

                        this.hasRetried = true;
                        gatt.close();
                        NativeGattPeripheral.this.gatt = BluetoothDeviceCompat.connectGatt(bluetoothDevice,
                                stack.applicationContext, autoConnect, gattDispatcher, transport);
                        if (NativeGattPeripheral.this.gatt != null) {
                            timeout.reschedule();
                        } else {
                            timeout.unschedule();

                            disconnectForwarder.setEnabled(true);
                            subscriber.onError(
                                    new GattException(GattException.GATT_INTERNAL_ERROR, Operation.CONNECT));
                        }

                        return true;
                    } else {
                        timeout.unschedule();

                        logger.error(LOG_TAG, "Could not connect. " + GattException.statusToString(status),
                                null);
                        disconnectForwarder.setEnabled(true);
                        subscriber.onError(new GattException(status, Operation.CONNECT));

                        return false;
                    }
                }
            };
            gattDispatcher.addConnectionListener(listener);

            timeout.setTimeoutAction(new Action0() {
                @Override
                public void call() {
                    timeout.unschedule();

                    gattDispatcher.removeConnectionListener(listener);
                    stopObservingBluetoothState();

                    disconnectForwarder.setEnabled(true);
                    subscriber.onError(new OperationTimeoutException(Operation.CONNECT));
                }
            }, stack.getScheduler());

            logger.info(LOG_TAG, "Connecting " + NativeGattPeripheral.this.toString());

            if (gatt != null) {
                if (gatt.connect()) {
                    disconnectForwarder.setEnabled(false);
                    timeout.schedule();
                } else {
                    gattDispatcher.removeConnectionListener(listener);

                    subscriber.onError(new GattException(GattException.GATT_INTERNAL_ERROR, Operation.CONNECT));
                }
            } else {
                NativeGattPeripheral.this.gatt = BluetoothDeviceCompat.connectGatt(bluetoothDevice,
                        stack.applicationContext, autoConnect, gattDispatcher, transport);
                if (gatt != null) {
                    disconnectForwarder.setEnabled(false);
                    timeout.schedule();
                } else {
                    gattDispatcher.removeConnectionListener(listener);

                    subscriber.onError(new GattException(GattException.GATT_INTERNAL_ERROR, Operation.CONNECT));
                }
            }
        }
    });
}