Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm trying to connect my Beacons to the Gattservice. In the Callback onConnectionStateChange, It's always failing and im getting the

statuscodes 133 and 257.

Somehwere was written that 133 stands for to many connections. In my code there are lines with gatt.disconnect(). I don't know how to fix it, because all other gattexamples are the same. I'm working with the Android 6.0.1 Version and the API 23, if it's important to find the error. Here's my code:

public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if(status == BluetoothGatt.GATT_SUCCESS) {
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    mBleDevices.add(gatt.getDevice());
                    Log.i("Beacons", "STATE_CONNECTED");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mBluetoothGatt.discoverServices();
                    break;
                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.e("Beacons", "STATE_DISCONNECTED");
                    mBleDevices.remove(gatt.getDevice());
                    mBluetoothGatt.disconnect();
                    mBluetoothGatt = null;
                    break;
                default:
                    Log.e("Beacons", "STATE_OTHER");
        } else {
            Log.e("Beacons", "ERROR WITH CONNECTING " + status);
            mBleDevices.remove(gatt.getDevice());

My ScanCallback looks like this:

 public void onScanResult(int callbackType, ScanResult result) {
    runOnUiThread(new Runnable() {
       @Override
       public void run() {
          BluetoothDevice btDevice = result.getDevice();
          connectToDevice(btDevice);

And starting connection like this:

 runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mBluetoothGatt = btDevice.connectGatt(getApplicationContext(), true, connectCallback);

The connectCallback causes then onConnectionStateChange function. Thank you for your help!

Michalik, you will get a scan callback multiple times, so the onScanResult() is calling multiple times and you are trying to connect the device for every callback i.e, you are trying to connect the device multiple times. Try to display the scan callback result in the listview and then connect to the respective device – Praveen Nov 24, 2017 at 12:12 yes, but this is a thing that should be done after the connection, am I right? if there's a connection, I call the gatt.getServices(), safe them in a variable and check if one of the service is the same that I want to have: gattServices.get(i).getUuid().equals(Battery_Service_UUID), and do further oprations on it. – Sunny Nov 24, 2017 at 12:16 If it comes to 257 error please read my comment here: https://stackoverflow.com/a/74812993/11509261 – kanoe Dec 15, 2022 at 15:02

On some Android devices, I see a 133 error on connect if the Android phone has not been paired (bonded) with the peripheral before. If I go to Settings -> Bluetooth at the same time as the app is trying to connect in the background, the connection works. (Strangely, you do not need to do anything on the screen, it just needs to be up.) Once this succeeds the first time, the error is gone forever.

I'm guessing this is a security restriction, but I have not figured the proper way to elegantly address it.

I had to specify the transport parameter in the call to fix this. It's an optional 4th paramater to specify it's a BLE device.

mBluetoothGatt = device.connectGatt(this, false, mGattCallback, 2);

https://developer.android.com/reference/android/bluetooth/BluetoothDevice#connectGatt(android.content.Context,%20boolean,%20android.bluetooth.BluetoothGattCallback,%20int)

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            ParcelUuid uuid = ParcelUuid.fromString("Your Beacon Service UUID");
            ScanFilter scanFilter = new ScanFilter.Builder().setServiceUuid(uuid).build();
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .setReportDelay(0)
                    .build();
            if (Build.VERSION.SDK_INT < 21) {
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
               mLEScanner.startScan(Collections.singletonList(scanFilter), settings, mScanCallback);
        } else {
            if (Build.VERSION.SDK_INT < 21) {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            } else {
                mLEScanner.stopScan(mScanCallback);
  

For scanCallBack

private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            Log.i("callbackType", String.valueOf(callbackType));
            Log.i("result", result.toString());
            BluetoothDevice btDevice = result.getDevice();
            connectToDevice(btDevice);
        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            for (ScanResult sr : results) {
                Log.i("ScanResult - Results", sr.toString());
        @Override
        public void onScanFailed(int errorCode) {
            Log.e("Scan Failed", "Error Code: " + errorCode);
private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi,
                                     byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.i("onLeScan", device.toString());
                            connectToDevice(device);
  

Connect the device

public void connectToDevice(BluetoothDevice device) {
    if (mGatt == null) {
        mGatt = device.connectGatt(this, false, gattCallback);
        scanLeDevice(false);// will stop after first device detection
  

gattcallback

 private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            Log.i("onConnectionStateChange", "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i("gattCallback", "STATE_CONNECTED");
                    gatt.discoverServices();
                    break;
                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.e("gattCallback", "STATE_DISCONNECTED");
                    break;
                default:
                    Log.e("gattCallback", "STATE_OTHER");
  

Then override onServicesDiscovered method.

okay, the error status are gone, but now, the code doesn't enter the mScanCallback. It only starts and stops the scan. Maybe the call scanLeDevice(false) is misplaced? – Sunny Nov 28, 2017 at 12:45 First you have to set scanLeDevice(true) and after device connected set scanLeDevice(false); – Shweta Chauhan Nov 28, 2017 at 12:49 for demo pupose on button click event put "scanLeDevice(true)" after device connected in "connectToDevice()" method set "scanLeDevice(false)". – Shweta Chauhan Nov 28, 2017 at 12:53 yes, okay I understand that, but it doesn't come to that part, that the device is getting connected and then I put the scanLeDevice(false), after a successful connection (in the gattCallback). after that an error appears. – Sunny Nov 28, 2017 at 13:47

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.