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

The following examples show how to use android.bluetooth.BluetoothGatt#close() . 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: CloseGattTransaction.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void transaction(GattTransactionCallback callback) {
    super.transaction(callback);
    getConnection().setState(GattState.CLOSING_GATT_CLIENT);
    BluetoothGatt localGatt = getConnection().getGatt();
    if(localGatt != null) {
        try {
            localGatt.close();
            getConnection().justClearGatt();
        } catch (NullPointerException e) {
            Timber.w(e, "[%s] If the underlying connection is gone, on some platforms, this can throw an NPE", getConnection().getDevice());
        }
    }
    getConnection().setState(GattState.CLOSE_GATT_CLIENT_SUCCESS);
    TransactionResult.Builder builder = new TransactionResult.Builder().transactionName(getName());
    builder.resultStatus(TransactionResult.TransactionResultStatus.SUCCESS);
    builder.gattState(getConnection().getGattState());
    mainThreadHandler.post(() -> {
        callCallbackWithTransactionResultAndRelease(callback, builder.build());
        getConnection().setState(GattState.DISCONNECTED);
    });
}
 
Example 3
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 4
Source File: DeviceServicesActivity.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
/**
 * CLEANS USER INTERFACE AND FINISH ACTIVITY
 *********************************************************/
public void exit(BluetoothGatt gatt) {
    gatt.close();
    if (service.getConnectedGatt() != null) {
        service.getConnectedGatt().close();
    }
    service.clearCache();
    bluetoothBinding.unbind();
    disconnect_gatt = false;
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            bluetoothGatt = null;
            service = null;
            bluetoothBinding = null;
            if (loadingdialog != null && loadingdialog.isShowing()) loadingdialog.dismiss();
            if (otaProgress != null && otaProgress.isShowing()) otaProgress.dismiss();
            if (otaSetup != null && otaSetup.isShowing()) otaSetup.dismiss();
            finish();
        }
    }, 1000);
}
 
Example 5
Source File: GattConnection.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
private void closeClientIf(BluetoothGatt localGatt) {
    try {
        localGatt.close();
    } catch (NullPointerException e) {
        // if we end up with an NPE here, it means that the underlying driver
        // didn't find the connection, this can happen with an unexpected
        // disconnection from the peripheral side which hasn't yet been realized
        // by the Android OS
        Timber.e(e, "[%s] Ran into OS Stack NPE", getDevice());
    }
}
 
Example 6
Source File: MyBleService.java    From science-journal with Apache License 2.0 5 votes vote down vote up
public boolean connect(String address) {
  if (btAdapter == null) {
    // Not sure how we could get here, but it happens (b/36738130), so flag an error
    // instead of crashing.
    return false;
  }
  BluetoothDevice device = btAdapter.getRemoteDevice(address);
  //  Explicitly check if Ble is enabled, otherwise it attempts a connection
  //  that never timesout even though it should.
  if (device == null || !isBleEnabled()) {
    return false;
  }
  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;
}
 
Example 7
Source File: GattManager.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    BluetoothDevice device = gatt.getDevice();

    Timber.d("device: %s, status: %d, newState: %d", (device != null), status, newState);

    if (BluetoothGatt.GATT_SUCCESS != status) {
        gatt.disconnect();
        return;
    }

    if (BluetoothProfile.STATE_DISCONNECTED == newState) {
        gatt.close();
    } else if (BluetoothProfile.STATE_CONNECTED == newState) {
        gatt.discoverServices();
        preferenceManager.addConnected(device.getAddress(), device.getName());
    }

    ThunderBoardDevice bgd = bleManager.getDeviceFromCache(device.getAddress());
    if (bgd != null) {
        bgd.setState(newState);
        bleManager.selectedDeviceMonitor.onNext(bgd);
        bleManager.selectedDeviceStatusMonitor.onNext(new StatusEvent(bgd));
    }
}
 
Example 8
Source File: BluetoothConnectManager.java    From AndroidBleManager with Apache License 2.0 5 votes vote down vote up
/**
 * close bluetooth, release resource
 * @param address
 */
public boolean close(String address) {
    if (!isEmpty(address) && gattMap.containsKey(address)){
        Logger.w("close gatt server " + address);
        BluetoothGatt mBluetoothGatt = gattMap.get(address);
        mBluetoothGatt.close();
        gattMap.remove(address);
        updateConnectStateListener(address, ConnectState.NORMAL);
        return true;
    }
    return false;
}
 
Example 9
Source File: DfuBaseService.java    From microbit with Apache License 2.0 5 votes vote down vote up
/**
 * Closes the GATT device and cleans up.
 *
 * @param gatt the GATT device to be closed
 */
private void close(final BluetoothGatt gatt) {
    logi("Cleaning up...");
    sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.close()");
    gatt.disconnect();
    gatt.close();
    mConnectionState = STATE_CLOSED;
}
 
Example 10
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 11
Source File: AndroidBle.java    From GizwitsBLE with Apache License 2.0 5 votes vote down vote up
@Override
public void disconnect(String address) {
	if (mBluetoothGatts.containsKey(address)) {
		BluetoothGatt gatt = mBluetoothGatts.remove(address);
		if (gatt != null) {
			gatt.disconnect();
			gatt.close();
		}
	}
}
 
Example 12
Source File: ESenseManager.java    From flutter-plugins with MIT License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        gatt.close();
        mCharacteristicMap.clear();
        if(mConnectionListener != null) {
            mConnectionListener.onDisconnected(ESenseManager.this);
        }
    }

}
 
Example 13
Source File: BleRequestImpl.java    From Android-BLE with Apache License 2.0 5 votes vote down vote up
/**
 * 清除蓝牙蓝牙连接设备的指定蓝牙地址
 *
 * @param address 蓝牙地址
 */
public void close(String address) {
    BluetoothGatt gatt = gattHashMap.get(address);
    if (gatt != null) {
        gatt.close();
        gattHashMap.remove(address);
    }
    connectedAddressList.remove(address);
}
 
Example 14
Source File: BluetoothUtilImpl.java    From android-ponewheel with MIT License 4 votes vote down vote up
private void onOWStateChangedToDisconnected(BluetoothGatt gatt, Context context) {
    //TODO: we really should have a BluetoothService we kill and restart
    Timber.i("We got disconnected from our Device: " + gatt.getDevice().getAddress());
    if (Looper.myLooper() == null) {
        Looper.prepare();
    }
    Toast.makeText(mainActivity, "We got disconnected from our device: " + gatt.getDevice().getAddress(), Toast.LENGTH_SHORT).show();

    mainActivity.deviceConnectedTimer(false);
    mOWDevice.isConnected.set(false);
    App.INSTANCE.releaseWakeLock();
    mScanResults.clear();

    if (App.INSTANCE.getSharedPreferences().shouldAutoReconnect()) {
        mRetryCount++;
        Timber.i("mRetryCount=" + mRetryCount);

        try {
            if (mRetryCount == 20) {
                Timber.i("Reached too many retries, stopping search");
                gatt.close();
                stopScanning();
                disconnect();
                //mainActivity.invalidateOptionsMenu();
            } else {
                Timber.i("Waiting for 5 seconds until trying to connect to OW again.");
                TimeUnit.SECONDS.sleep(5);
                Timber.i("Trying to connect to OW at " + mOWDevice.deviceMacAddress.get());
                //BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mOWDevice.deviceMacAddress.get());
                //connectToDevice(device);
                gatt.connect();
            }
        } catch (InterruptedException e) {
            Timber.d("Connection to OW got interrupted:" + e.getMessage());
        }
    } else {
        gatt.close();
        mainActivity.invalidateOptionsMenu();
    }

}
 
Example 15
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 16
Source File: BluetoothManager.java    From tap-android-sdk with Apache License 2.0 4 votes vote down vote up
private void closeGatt(BluetoothGatt gatt) {
    removeExecutor(getExecutor(gatt));
    gatt.close();
}
 
Example 17
Source File: BleConnectionCompat.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
public BluetoothGatt connectGatt(BluetoothDevice remoteDevice, boolean autoConnect, BluetoothGattCallback bluetoothGattCallback) {

        if (remoteDevice == null) {
            return null;
        }

        /**
         * Issue that caused a race condition mentioned below was fixed in 7.0.0_r1
         * https://android.googlesource.com/platform/frameworks/base/+/android-7.0.0_r1/core/java/android/bluetooth/BluetoothGatt.java#649
         * compared to
         * https://android.googlesource.com/platform/frameworks/base/+/android-6.0.1_r72/core/java/android/bluetooth/BluetoothGatt.java#739
         * issue: https://android.googlesource.com/platform/frameworks/base/+/d35167adcaa40cb54df8e392379dfdfe98bcdba2%5E%21/#F0
          */
        if (Build.VERSION.SDK_INT >= 24 /* Build.VERSION_CODES.N */ || !autoConnect) {
            return connectGattCompat(bluetoothGattCallback, remoteDevice, autoConnect);
        }

        /**
         * Some implementations of Bluetooth Stack have a race condition where autoConnect flag
         * is not properly set before calling connectGatt. That's the reason for using reflection
         * to set the flag manually.
         */

        try {
            RxBleLog.v("Trying to connectGatt using reflection.");
            Object iBluetoothGatt = getIBluetoothGatt(getIBluetoothManager());

            if (iBluetoothGatt == null) {
                RxBleLog.w("Couldn't get iBluetoothGatt object");
                return connectGattCompat(bluetoothGattCallback, remoteDevice, true);
            }

            BluetoothGatt bluetoothGatt = createBluetoothGatt(iBluetoothGatt, remoteDevice);

            if (bluetoothGatt == null) {
                RxBleLog.w("Couldn't create BluetoothGatt object");
                return connectGattCompat(bluetoothGattCallback, remoteDevice, true);
            }

            boolean connectedSuccessfully = connectUsingReflection(bluetoothGatt, bluetoothGattCallback, true);

            if (!connectedSuccessfully) {
                RxBleLog.w("Connection using reflection failed, closing gatt");
                bluetoothGatt.close();
            }

            return bluetoothGatt;
        } catch (NoSuchMethodException
                | IllegalAccessException
                | IllegalArgumentException
                | InvocationTargetException
                | InstantiationException
                | NoSuchFieldException exception) {
            RxBleLog.w(exception, "Error while trying to connect via reflection");
            return connectGattCompat(bluetoothGattCallback, remoteDevice, true);
        }
    }
 
Example 18
Source File: AmazonFreeRTOSDevice.java    From amazon-freertos-ble-android-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                    int newState) {
    Log.i(TAG, "BLE connection state changed: " + status + "; new state: "
            + AmazonFreeRTOSConstants.BleConnectionState.values()[newState]);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            int bondState = mBluetoothDevice.getBondState();

            mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_CONNECTED;
            Log.i(TAG, "Connected to GATT server.");
            // If the device is already bonded or will not bond we can call discoverServices() immediately
            if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDED) {
                discoverServices();
            }
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED;
            Log.i(TAG, "Disconnected from GATT server.");

            // If ble connection is closed, there's no need to keep mqtt connection open.
            if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
                disconnectFromIot();
            }

            // If not using auto reconnect or if user initiated disconnect
            if (!mGattAutoReconnect) {
                gatt.close();
                mBluetoothGatt = null;
            }
            cleanUp();
        }
    } else {
        Log.i(TAG, "Disconnected from GATT server due to error ot peripheral initiated disconnect.");

        mBleConnectionState = AmazonFreeRTOSConstants.BleConnectionState.BLE_DISCONNECTED;

        if (mMqttConnectionState != AmazonFreeRTOSConstants.MqttConnectionState.MQTT_Disconnected) {
            disconnectFromIot();
        }

        if (!mGattAutoReconnect) {
            gatt.close();
            mBluetoothGatt = null;
        }
        cleanUp();
    }
    mBleConnectionStatusCallback.onBleConnectionStatusChanged(mBleConnectionState);
}
 
Example 19
Source File: MyBleService.java    From science-journal with Apache License 2.0 4 votes vote down vote up
void resetGatt() {
  for (BluetoothGatt bluetoothGatt : addressToGattClient.values()) {
    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();

}