Android intermittent Bluetooth connection error's

I created a basic application to test connecting to beacons and retrieving accelerator information. There seems to be some form of intermittent Bluetooth error. The application works, then it doesn’t then it does;

When establishing the connection, the device consistently fires the BeaconConnection.ConnectionCallback() public void onAuthorized(BeaconInfo beaconInfo) method.

However, half the time, BeaconConnection.ConnectionCallback() @Override public void onAuthenticationError(EstimoteDeviceException exception) is fired…

I have attached both the main code, and the logs of the running application. Thanks for any input.

package life.secret.package;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.EstimoteSDK;
import com.estimote.sdk.Region;
import com.estimote.sdk.SystemRequirementsChecker;
import com.estimote.sdk.cloud.model.BeaconInfo;
import com.estimote.sdk.connection.BeaconConnection;
import com.estimote.sdk.connection.MotionState;
import com.estimote.sdk.connection.Property;
import com.estimote.sdk.exception.EstimoteDeviceException;

import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity
{
    private static final UUID ESTIMOTE_PROXIMITY_UUID = UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FE6D");
    private static final Region ALL_ESTIMOTE_BEACONS = new Region("rid", ESTIMOTE_PROXIMITY_UUID, null, null);

    Beacon beacon;
    BeaconConnection connection;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        EstimoteSDK.initialize(this, "secret", "information");

        LayoutInflater li = getLayoutInflater();
        View mainView = li.inflate(R.layout.activity_main, null);
        setContentView(mainView);
        Toolbar toolbar = (Toolbar)mainView.findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Button closeConnection = (Button)mainView.findViewById(R.id.closeConnection);
        closeConnection.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                connection.close();
            }
        });

        final TextView textView = (TextView)mainView.findViewById(R.id.textView);
        final BeaconManager beaconManager = new BeaconManager(this);
        FloatingActionButton fab = (FloatingActionButton)mainView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                beaconManager.disconnect();
            }
        });

        beaconManager.setForegroundScanPeriod(3000, 10000);

        beaconManager.setRangingListener(new BeaconManager.RangingListener()
        {
            @Override
            public void onBeaconsDiscovered(Region region, final List beacons)
            {
                if(beacons.size() > 0)
                {
                    beacon = (Beacon)beacons.get(0);

                    connection = new BeaconConnection(MainActivity.this, beacon, new BeaconConnection.ConnectionCallback() {
                        @Override
                        public void onAuthorized(BeaconInfo beaconInfo)
                        {
                            Log.d("TEST", "Authorized beacon. Info: " + beaconInfo);
                        }
                        @Override public void onConnected(BeaconInfo beaconInfo) {
                            Log.d("TEST", "Authenticated to beacon. Info: " + beaconInfo);
                            Log.d("TEST", "Advertising internal: " + connection.advertisingIntervalMillis().get());
                            Log.d("TEST", "Broadcasting transmitPower: " + connection.broadcastingPower().get());

                            connection.setMotionListener(new Property.Callback<MotionState>(){
                                @Override public void onFailure()
                                {
                                    runOnUiThread(new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            textView.setText("Something went wrong...");
                                            connection.close();
                                        }
                                    });
                                }
                                @Override public void onValueReceived(final MotionState value)
                                {
                                    runOnUiThread(new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            textView.setText("Got motion...:" + value.toString());
                                            connection.close();
                                        }
                                    });
                                }
                            });
                        }

                        @Override public void onAuthenticationError(EstimoteDeviceException exception) {
                            Log.d("TEST", "Authentication Error: " + exception);
                        }

                        @Override public void onDisconnected() {
                            Log.d("TEST", "Disconnected");
                        }
                    });

                    connection.authenticate();
                }
                Log.v("ESTIMOTE DATA:", "Ranged beacons: " + beacons);
            }
        });

        beaconManager.connect(new BeaconManager.ServiceReadyCallback()
        {
            @Override
            public void onServiceReady()
            {
                beaconManager.startRanging(ALL_ESTIMOTE_BEACONS);
            }
        });
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        SystemRequirementsChecker.checkWithDefaultDialogs(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if(id == R.id.action_settings)
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Here are the running logs.

03-24 16:23:24.473 3437-3475/life.lighhousemedical.estimotetest D/BluetoothAdapter: stopLeScan()
03-24 16:23:24.513 3437-3437/life.lighhousemedical.estimotetest V/ESTIMOTE DATA:: Ranged beacons: [Beacon{macAddress=[DB:8E:CA:BA:64:CE], proximityUUID=b9407f30-f5f8-466e-aff9-25556b57fe6d, major=25806, minor=51898, measuredPower=-60, rssi=-62}]
03-24 16:23:24.613 3437-5229/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-24 16:23:24.613 3437-5229/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Static: isShipBuild true
03-24 16:23:24.613 3437-5229/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Thread-3838-397848972: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
03-24 16:23:24.613 3437-5229/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Thread-3838-397848972: SMARTBONDING_FEATURE_ENABLED is false
03-24 16:23:24.613 3437-5229/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-24 16:23:24.623 3437-5229/life.lighhousemedical.estimotetest I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
03-24 16:23:25.743 3437-3437/life.lighhousemedical.estimotetest D/TEST: Authorized beacon. Info: BeaconInfo{uuid='b9407f30-f5f8-466e-aff9-25556b57fe6d', major=25806, minor=51898, macAddress='[DB:8E:CA:BA:64:CE]', name='Wolf Rock', color=Mint Cocktail, batteryLifeExpectancyInDays=1014.0, settings=BeaconInfoSettings{batteryLevel=100, hardware='D3.4', firmware='A3.2.0', broadcastingPower=LEVEL_8, advertisingIntervalMillis=1019, basicPowerMode=true, smartPowerMode=false, conditionalBroadcasting=FLIP_TO_SLEEP, broadcastingScheme=ESTIMOTE_DEFAULT, isFirmwareUpToDate=true, eddystoneNamespace='null', eddystoneInstance='null', eddystoneUrl='null', secure='false'}}
03-24 16:23:25.743 3437-3437/life.lighhousemedical.estimotetest D/BluetoothGatt: connect() - device: DB:8E:CA:BA:64:CE, auto: false
03-24 16:23:25.743 3437-3437/life.lighhousemedical.estimotetest D/BluetoothGatt: registerApp()
03-24 16:23:25.743 3437-3437/life.lighhousemedical.estimotetest D/BluetoothGatt: registerApp() - UUID=1c4dc609-d850-40df-8f59-40e679e8cc6b
03-24 16:23:25.783 3437-3446/life.lighhousemedical.estimotetest D/BluetoothGatt: onClientRegistered() - status=0 clientIf=6
03-24 16:23:26.633 3437-3437/life.lighhousemedical.estimotetest D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
03-24 16:23:30.793 3437-3508/life.lighhousemedical.estimotetest D/BluetoothGatt: onClientConnectionState() - status=133 clientIf=6 device=DB:8E:CA:BA:64:CE
03-24 16:23:30.793 3437-3508/life.lighhousemedical.estimotetest W/EstimoteSDK: com.estimote.sdk.connection.internal.bluerock.BlueRock$1.onConnectionStateChange:104 Disconnected from GATT server (we were trying to connect, status=133)
03-24 16:23:30.793 3437-3508/life.lighhousemedical.estimotetest D/BluetoothGatt: close()
03-24 16:23:30.793 3437-3508/life.lighhousemedical.estimotetest D/BluetoothGatt: unregisterApp() - mClientIf=6
03-24 16:23:30.793 3437-3508/life.lighhousemedical.estimotetest D/TEST: Authentication Error: com.estimote.sdk.exception.EstimoteDeviceException: Disconnected from beacon while trying to connect
03-24 16:23:35.123 3437-3475/life.lighhousemedical.estimotetest D/BluetoothAdapter: startLeScan(): null
03-24 16:23:35.173 3437-3508/life.lighhousemedical.estimotetest D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=6
03-24 16:23:36.153 3437-3447/life.lighhousemedical.estimotetest D/ScanRecord: parseFromBytes
03-24 16:23:36.153 3437-3447/life.lighhousemedical.estimotetest D/ScanRecord: first manudata for manu ID
03-24 16:23:36.153 3437-3447/life.lighhousemedical.estimotetest D/BluetoothLeScanner: onScanResult() - ScanResult{mDevice=DB:8E:CA:BA:64:CE, mScanRecord=ScanRecord [mAdvertiseFlags=6, mServiceUuids=[0000180f-0000-1000-8000-00805f9b34fb], mManufacturerSpecificData={76=[2, 21, -71, 64, 127, 48, -11, -8, 70, 110, -81, -7, 37, 85, 107, 87, -2, 109, 100, -50, -54, -70, -60]}, mServiceData={0000180a-0000-1000-8000-00805f9b34fb=[-50, 100, -70, -54, -114, -37, -60, -50, 100, -70, -54]}, mTxPowerLevel=-2147483648, mDeviceName=EST], mRssi=-58, mTimestampNanos=2346730688216}
03-24 16:23:37.153 3437-3446/life.lighhousemedical.estimotetest D/ScanRecord: parseFromBytes
03-24 16:23:37.153 3437-3446/life.lighhousemedical.estimotetest D/ScanRecord: first manudata for manu ID
03-24 16:23:37.153 3437-3446/life.lighhousemedical.estimotetest D/BluetoothLeScanner: onScanResult() - ScanResult{mDevice=DB:8E:CA:BA:64:CE, mScanRecord=ScanRecord [mAdvertiseFlags=6, mServiceUuids=[0000180f-0000-1000-8000-00805f9b34fb], mManufacturerSpecificData={76=[2, 21, -71, 64, 127, 48, -11, -8, 70, 110, -81, -7, 37, 85, 107, 87, -2, 109, 100, -50, -54, -70, -60]}, mServiceData={0000180a-0000-1000-8000-00805f9b34fb=[-50, 100, -70, -54, -114, -37, -60, -50, 100, -70, -54]}, mTxPowerLevel=-2147483648, mDeviceName=EST], mRssi=-70, mTimestampNanos=2347734297903}
03-24 16:23:38.173 3437-3508/life.lighhousemedical.estimotetest D/ScanRecord: parseFromBytes
03-24 16:23:38.173 3437-3508/life.lighhousemedical.estimotetest D/ScanRecord: first manudata for manu ID
03-24 16:23:38.173 3437-3508/life.lighhousemedical.estimotetest D/BluetoothLeScanner: onScanResult() - ScanResult{mDevice=DB:8E:CA:BA:64:CE, mScanRecord=ScanRecord [mAdvertiseFlags=6, mServiceUuids=[0000180f-0000-1000-8000-00805f9b34fb], mManufacturerSpecificData={76=[2, 21, -71, 64, 127, 48, -11, -8, 70, 110, -81, -7, 37, 85, 107, 87, -2, 109, 100, -50, -54, -70, -60]}, mServiceData={0000180a-0000-1000-8000-00805f9b34fb=[-50, 100, -70, -54, -114, -37, -60, -50, 100, -70, -54]}, mTxPowerLevel=-2147483648, mDeviceName=EST], mRssi=-67, mTimestampNanos=2348756570090}
03-24 16:23:38.193 3437-3475/life.lighhousemedical.estimotetest D/BluetoothAdapter: stopLeScan()
03-24 16:23:38.213 3437-3437/life.lighhousemedical.estimotetest D/BluetoothManager: getConnectionState()
03-24 16:23:38.213 3437-3437/life.lighhousemedical.estimotetest D/BluetoothManager: getConnectedDevices
03-24 16:23:38.223 3437-3437/life.lighhousemedical.estimotetest V/ESTIMOTE DATA:: Ranged beacons: [Beacon{macAddress=[DB:8E:CA:BA:64:CE], proximityUUID=b9407f30-f5f8-466e-aff9-25556b57fe6d, major=25806, minor=51898, measuredPower=-60, rssi=-69}]
03-24 16:23:38.223 3437-5229/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-24 16:23:38.743 3437-3437/life.lighhousemedical.estimotetest D/TEST: Authorized beacon. Info: BeaconInfo{uuid='b9407f30-f5f8-466e-aff9-25556b57fe6d', major=25806, minor=51898, macAddress='[DB:8E:CA:BA:64:CE]', name='Wolf Rock', color=Mint Cocktail, batteryLifeExpectancyInDays=1014.0, settings=BeaconInfoSettings{batteryLevel=100, hardware='D3.4', firmware='A3.2.0', broadcastingPower=LEVEL_8, advertisingIntervalMillis=1019, basicPowerMode=true, smartPowerMode=false, conditionalBroadcasting=FLIP_TO_SLEEP, broadcastingScheme=ESTIMOTE_DEFAULT, isFirmwareUpToDate=true, eddystoneNamespace='null', eddystoneInstance='null', eddystoneUrl='null', secure='false'}}
03-24 16:23:38.753 3437-3437/life.lighhousemedical.estimotetest D/BluetoothGatt: connect() - device: DB:8E:CA:BA:64:CE, auto: false
03-24 16:23:38.753 3437-3437/life.lighhousemedical.estimotetest D/BluetoothGatt: registerApp()
03-24 16:23:38.753 3437-3437/life.lighhousemedical.estimotetest D/BluetoothGatt: registerApp() - UUID=c9f663b6-4499-404b-9ca2-576a63a8ae99
03-24 16:23:38.803 3437-3508/life.lighhousemedical.estimotetest D/BluetoothGatt: onClientRegistered() - status=0 clientIf=6
03-24 16:23:39.433 3437-3447/life.lighhousemedical.estimotetest D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=6 device=DB:8E:CA:BA:64:CE
03-24 16:23:39.433 3437-3447/life.lighhousemedical.estimotetest D/BluetoothGatt: discoverServices() - device: DB:8E:CA:BA:64:CE
03-24 16:23:40.503 3437-3508/life.lighhousemedical.estimotetest D/BluetoothGatt: onSearchComplete() = Device=DB:8E:CA:BA:64:CE Status=0
03-24 16:23:40.663 3437-6142/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-24 16:23:42.623 3437-6142/life.lighhousemedical.estimotetest I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-24 16:23:43.543 3437-3437/life.lighhousemedical.estimotetest D/TEST: Authenticated to beacon. Info: BeaconInfo{uuid='b9407f30-f5f8-466e-aff9-25556b57fe6d', major=25806, minor=51898, macAddress='[DB:8E:CA:BA:64:CE]', name='Wolf Rock', color=Mint Cocktail, batteryLifeExpectancyInDays=1014.0, settings=BeaconInfoSettings{batteryLevel=100, hardware='D3.4', firmware='A3.2.0', broadcastingPower=LEVEL_8, advertisingIntervalMillis=1019, basicPowerMode=true, smartPowerMode=false, conditionalBroadcasting=FLIP_TO_SLEEP, broadcastingScheme=ESTIMOTE_DEFAULT, isFirmwareUpToDate=true, eddystoneNamespace='null', eddystoneInstance='null', eddystoneUrl='null', secure='false'}}
03-24 16:23:43.543 3437-3437/life.lighhousemedical.estimotetest D/TEST: Advertising internal: 1019
03-24 16:23:43.553 3437-3437/life.lighhousemedical.estimotetest D/TEST: Broadcasting transmitPower: LEVEL_8

What exact SDK version are you using and on what phone you are experiencing this behavior and which Android version it is running?
It seems that a new connection is opened in onBeaconsDiscovered which is called every 3 seconds. Connecting to beacon may take longer than 3 s (Cloud communication + Bluetooth stack) and in the meantime a new connection is being opened. Beacon can only handle one connection and following attempts will end with an error (usually with 133 - Generic GATT error). Sometimes it may work because Proximity Beacon stops advertising when connection is opened and onBeaconsDiscovered will return empty list.
Make sure that you are opening only one connection per time (for example add a flag isConnecting). You can also stop ranging when connection to beacon is established.
There is a new API for connecting to beacons since SDK 0.10.0 that allows to connect both to Proximity Beacons (old ones) and Location Beacons (new ones). This means that current way of connecting using BeaconConnection will no longer be developed, will be deprecated and might be removed from SDK.
More information about connecting to beacons using new API can be found here: https://github.com/Estimote/Android-SDK/blob/master/DOC_deviceConnection.md