This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

How to return BLE peripheral's connection status

I'm writing an Android application that connects to various BLE peripherals including the NRF51 and NRF52. I don't know if this question is appropriate for this site, but here it goes.

I noticed that the method onConnectionStateChange() from Android ble API is not invariably invoked (or just not invoked on time) when a peripheral is non-manually disconnected like for example when the peripheral is powered off. Is there a way to get the connection state of a connected BLE peripheral manually versus just waiting for the onConnectionStateChange() to fire? I tried using BluetoothManager#getConnectionState but this method seems to be accessing the connection state updated by whatever thread is calling onConnectionStateChange(), and does not actually ask the device if it's connected. In other words, BluetoothManager#getConnectionState just returns false if onConnectionStateChange() hasn't been called yet.

Here is my isConnected method in an Android application I'm writing

public boolean isConnected(){
    
    // If the device has never connected, it's gatt service is null.
    if(mGatt != null){
    
        BluetoothManager btm =
                (BluetoothManager)
                        MainActivity.mMainActivity.getSystemService(Context.BLUETOOTH_SERVICE);
                        
        int state = btm.getConnectionState(mGatt.getDevice(), BluetoothProfile.GATT);

        return state == 2;
    }

    // The gat service is null, the device is not connected, return false.
    return false;
}
Related