Java Code Examples for android.bluetooth.BluetoothGatt#disconnect()

The following examples show how to use android.bluetooth.BluetoothGatt#disconnect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Ble.java    From JayPS-AndroidApp with MIT License 7 votes vote down vote up
public void disconnectAllDevices() {
    if (mBluetoothAdapter == null) {
        Log.w(TAG, "disconnectAllDevices BluetoothAdapter not initialized");
        return;
    }
    Log.d(TAG, "disconnectAllDevices mGatts.size:" + mGatts.size());
    Iterator<Map.Entry<String, BluetoothGatt>> iterator = mGatts.entrySet().iterator();
    while (iterator.hasNext()) {
        BluetoothGatt gatt = iterator.next().getValue();
        Log.d(TAG, "disconnect" + display(gatt));
        if (gatt != null) {
            gatt.disconnect();
            gatt.close();
            //gatt = null;
        }
    }
    mGatts.clear();
    if (connectionThread != null) {
        connectionThread.interrupt();
        connectionThread = null;
    }
}
 
Example 2
Source File: HandleTrackerVanishingUnderGattOperationStrategy.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void applyStrategy() {
    Timber.d("Applying tracker vanishing while in gatt operation strategy");
    if(connection != null) {
        connection.setState(GattState.DISCONNECTING);
        BluetoothGatt localGatt = connection.getGatt();
        if(localGatt != null) {
            localGatt.disconnect();
        } else {
            Timber.d("Could not apply strategy because the gatt was null");
        }
    }
    // we might not get the gatt disconnect callback if the if is lost,
    // so in this scenario we will have to wait for the client_if to dump for sure,
    // at least 1s on pixel
    Timber.v("Waiting %dms for the client_if to dump", WAIT_TIME_FOR_DISCONNECTION);
    if(connection != null) {
        connection.getMainHandler().postDelayed(() -> {
            connection.setState(GattState.DISCONNECTED);
            if (FitbitGatt.getInstance().getServer() != null) {
                FitbitGatt.getInstance().getServer().setState(GattState.DISCONNECTED);
            }
            Timber.v("Strategy is done, gatt can be used again");
        }, WAIT_TIME_FOR_DISCONNECTION);
    }
}
 
Example 3
Source File: BTConnectionManager.java    From Mi-Band with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    //Log.e(TAG, "onConnectionStateChange (2): " + newState);

    BTConnectionManager.this.gatt = gatt;

    if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
        gatt.discoverServices();
    } else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED) {
        //Log.e(TAG, "onConnectionStateChange disconnect: " + newState);
        //toggleNotifications(false);
        //disconnect();
    } else if (status != BluetoothGatt.GATT_SUCCESS) {
        gatt.disconnect();
    }
}
 
Example 4
Source File: MyBleService.java    From science-journal with Apache License 2.0 6 votes vote down vote up
public void disconnectDevice(String address) {
  BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
  if (btAdapter == null || address == null || bluetoothGatt == null) {
    // Broadcast the disconnect so BleFlow doesn't hang waiting for it; something else
    // already disconnected us in this case.
    sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
    return;
  }
  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);
  }
}
 
Example 5
Source File: Device.java    From neatle with MIT License 6 votes vote down vote up
@Override
public void disconnect() {
    NeatleLogger.i("Disconnecting");
    stopDiscovery();
    BluetoothGatt target;
    int oldState;

    synchronized (lock) {
        target = gatt;
        gatt = null;
        this.serviceDiscovered = false;
        oldState = state;
        state = BluetoothGatt.STATE_DISCONNECTED;
    }
    if (target != null) {
        target.disconnect();
    }
    notifyConnectionStateChange(oldState, BluetoothGatt.STATE_DISCONNECTED);
}
 
Example 6
Source File: UpdateService.java    From Android-nRF-Beacon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
	if (status != BluetoothGatt.GATT_SUCCESS) {
		logw("Service discovery error: " + status);
		broadcastError(status);
		return;
	}

	// We have successfully connected
	setState(STATE_CONNECTED);

	// Search for config service
	final BluetoothGattService configService = gatt.getService(CONFIG_SERVICE_UUID);
	if (configService == null) {
		// Config service is not present
		broadcastError(ERROR_UNSUPPORTED_DEVICE);
		setState(STATE_DISCONNECTING);
		gatt.disconnect();
		return;
	}

	mUuidCharacteristic = configService.getCharacteristic(CONFIG_UUID_CHARACTERISTIC_UUID);
	mMajorMinorCharacteristic = configService.getCharacteristic(CONFIG_MAJOR_MINOR_CHARACTERISTIC_UUID);
	mRssiCharacteristic = configService.getCharacteristic(CONFIG_RSSI_CHARACTERISTIC_UUID);
	mManufacturerIdCharacteristic = configService.getCharacteristic(CONFIG_MANUFACTURER_ID_CHARACTERISTIC_UUID);
	mAdvIntervalCharacteristic = configService.getCharacteristic(CONFIG_ADV_INTERVAL_CHARACTERISTIC_UUID);
	mLedSettingsCharacteristic = configService.getCharacteristic(CONFIG_LED_SETTINGS_CHARACTERISTIC_UUID);

	if (mUuidCharacteristic != null || mMajorMinorCharacteristic != null || mRssiCharacteristic != null)
		broadcastOperationCompleted(mManufacturerIdCharacteristic != null || mAdvIntervalCharacteristic != null || mLedSettingsCharacteristic != null);

	if (mUuidCharacteristic == null && mMajorMinorCharacteristic == null && mRssiCharacteristic == null) {
		// Config characteristics is not present
		broadcastError(ERROR_UNSUPPORTED_DEVICE);
		setState(STATE_DISCONNECTING);
		gatt.disconnect();
	}
}
 
Example 7
Source File: GattConnection.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will unregister this process from the system so no further callback will be delivered, note
 * this does not actually disconnect the remote peripheral
 */

public void disconnect() {
    if (mockMode) {
        mockDisconnect();
        return;
    }
    BluetoothGatt localGatt = gatt;
    if (localGatt == null) {
        setState(GattState.DISCONNECTED);
    } else {
        /*
         * It is important to note that after disconnect is processed, there can be a long
         * supervision timeout if the device disconnects itself, the state will remain
         * {@link GattState.DISCONNECTING} until that is complete ...
         */
        try {
            localGatt.disconnect();
        } catch (NullPointerException e) {
            // this means that the hardware's underlying connection went away while
            // we were trying to cancel a connection attempt
            // there are a number of phones that have this flaw, we don't need to do
            // anything though, if this NPEs it means that the connection is already
            // cancelled ... there is nothing there to cancel
            Timber.e(e, "[%s] OS Stack Failure while disconnecting", getDevice());
        }
        setState(GattState.DISCONNECTING);
    }
}
 
Example 8
Source File: G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
Example 9
Source File: G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
Example 10
Source File: G5CollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
Example 11
Source File: MkrSciBleManager.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
    this.gatt = gatt;
    characteristics.clear();
    gatt.discoverServices();
  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
    readyForAction = false;
    gatt.disconnect();
  }
}
 
Example 12
Source File: HeartRateConnector.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * Disconnect to the bluetooth device.
 *
 * @param device bluetooth device
 */
public void disconnectDevice(final BluetoothDevice device) {
    if (device == null) {
        throw new IllegalArgumentException("device is null");
    }
    String address = device.getAddress();
    synchronized (mHRDevices) {
        for (BluetoothGatt gatt : mHRDevices.keySet()) {
            if (gatt.getDevice().getAddress().equalsIgnoreCase(address)) {
                gatt.disconnect();
            }
        }
    }
    mRegisterDevices.remove(device.getAddress());
}
 
Example 13
Source File: DfuBaseService.java    From microbit with Apache License 2.0 5 votes vote down vote up
/**
 * Disconnects from the device. This is SYNCHRONOUS method and waits until the callback returns new state. Terminates immediately if device is already disconnected. Do not call this method
 * directly, use {@link #terminateConnection(android.bluetooth.BluetoothGatt, int)} instead.
 *
 * @param gatt the GATT device that has to be disconnected
 */
private void disconnect(final BluetoothGatt gatt) {
    if (mConnectionState == STATE_DISCONNECTED)
        return;

    mConnectionState = STATE_DISCONNECTING;
    logi("Disconnecting from the device...");
    gatt.disconnect();

    // We have to wait until device gets disconnected or an error occur
    waitUntilDisconnected();
}
 
Example 14
Source File: BluetoothConnectManager.java    From AndroidBleManager with Apache License 2.0 5 votes vote down vote up
/**
 * 断开蓝牙连接,不会释放BluetoothGatt持有的所有资源,可以调用mBluetoothGatt.connect()很快重新连接上
 * 如果不及时释放资源,可能出现133错误,http://www.loverobots.cn/android-ble-connection-solution-bluetoothgatt-status-133.html
 * @param address
 */
public void disconnect(String address){
    if (!isEmpty(address) && gattMap.containsKey(address)){
        reconnectParamsBean = new ReconnectParamsBean(address);
        reconnectParamsBean.setNumber(1000);
        Logger.w("disconnect gatt server " + address);
        BluetoothGatt mBluetoothGatt = gattMap.get(address);
        mBluetoothGatt.disconnect();
        updateConnectStateListener(address, ConnectState.NORMAL);
    }
}
 
Example 15
Source File: LightActivity.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        BluetoothGatt gatt = service.getConnectedGatt();
        gatt.disconnect();
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
 
Example 16
Source File: BleService.java    From bleTester with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
public void close(BluetoothGatt gatt) {
	gatt.disconnect();
	gatt.close();
	if (mBluetoothAdapter != null) {
		mBluetoothAdapter.cancelDiscovery();
		mBluetoothAdapter = null;
	}
}
 
Example 17
Source File: BLEPeripheralDefault.java    From itag with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void disconnect() {
    if (BLEPeripheralState.disconnected.equals(state)) {
        if (BuildConfig.DEBUG) {
            Log.d(LT, "disconnect id=" + identifier() + ", already disconnected, no action");
        }
    } else {
        BluetoothGatt gatt = gatt();
        boolean connected = isConnected();
        if (connected && gatt!=null) {
            if (BuildConfig.DEBUG) {
                Log.d(LT, "disconnect id=" + identifier() + ", connected, will wait connection change");
            }
            setState(BLEPeripheralState.disconnecting);
            gatt.disconnect();
        } else {
            if (BuildConfig.DEBUG) {
                Log.d(LT, "disconnect id=" + identifier() + ", not connected will simulate connection change");
            }
            setState(BLEPeripheralState.disconnecting);
            if (gatt != null)
                    gatt.disconnect(); // just in case ?
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            close();
            observables.channelDisconnected.broadcast(new BLEPeripheralObservablesInterface.DisconnectedEvent(0));
        }
    }
}
 
Example 18
Source File: ConnectRequestQueue.java    From AndroidBleManager with Apache License 2.0 5 votes vote down vote up
/**
 * 断开蓝牙连接,不会释放BluetoothGatt持有的所有资源,可以调用mBluetoothGatt.connect()很快重新连接上
 * 如果不及时释放资源,可能出现133错误,http://www.loverobots.cn/android-ble-connection-solution-bluetoothgatt-status-133.html
 * @param address
 */
public void disconnect(String address){
    if (!isEmpty(address) && gattMap.containsKey(address)){
        Logger.w("disconnect gatt server " + address);
        BluetoothGatt mBluetoothGatt = gattMap.get(address);
        mBluetoothGatt.disconnect();
        updateConnectState(address, ConnectState.NORMAL);
    }
}
 
Example 19
Source File: BlueToothService.java    From EFRConnect-android with Apache License 2.0 4 votes vote down vote up
private void clearGatt(BluetoothGatt bluetoothGatt) {
    bluetoothGatt.disconnect();
    bluetoothGatt.close();
}
 
Example 20
Source File: TestBeanBLE.java    From bean-sdk-android with MIT License 3 votes vote down vote up
@Suppress
public void testBLE() throws InterruptedException {

    // Scan/Discover
    BluetoothDevice device = findDevice();

    // Connect to closest device (hopefully a Bean)
    BluetoothGatt gatt = connectGatt(device);

    // Clear Android Cache
    refreshDeviceCache(gatt);

    // Discover services
    discoverServices(gatt);

    // Read HW version from Device Info Service
    readHardwareVersion(gatt);

    // Enable notifications on OAD Identify char
    enableNotificationOADIdentify(gatt);

    // Write 0x0000 to OAD Identify char
    writeCharacteristicOADIdentify(gatt);

    // Receive notification
    receiveNotificationOADIdentify();

    gatt.disconnect();
    gatt.close();

}