Animesh Jena
Animesh Jena

Reputation: 1551

Unable to disconnect and reconnect to BLE tool android

I am working on BLE connection in my app. Everything works fine until I press the back button. On pressing the back button, the BLE connection should disconnect and again on activity loading It tries to connect to the tool. While the activity loads, I still get gatt != null as true. I am unable to findout the issue. I think there are some issues in my code in onConnectionStateChanged(), Service disconnected. I will post my code below. Please have a look.

llBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


                FragmentManager fragmentManager = mContext.getSupportFragmentManager();
                BleUtil.disconnect_tool();
                fragmentManager.popBackStack();
                mContext.recreate();
            }

In side BleUtil class:

 public static void disconnect_tool()
{
    mBluetoothGatt.disconnect();
}

Inside OnConnectionStateChaged():

 private BluetoothGattCallback gattCallback =
        new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
            {

                if (newState == STATE_CONNECTED) {
                    gattInterface.onToolConnected();
                    gatt.discoverServices();

                    Toast.makeText(activity,"Connected",Toast.LENGTH_SHORT).show();

                } else if (newState == STATE_DISCONNECTED) {


                    //disconnect_tool();
                    gatt.close();
                    mBluetoothGatt.close();
                    gatt = null;
                    mBluetoothGatt = null;

                    gattInterface.onToolDisconnected();
                    Log.d("checkdisco","disconn");
                  //  mConnectionState = STATE_DISCONNECTED;
                    Toast.makeText(activity,"Disconnected",Toast.LENGTH_SHORT).show();
                //    gatt.close();


                    if(gatt != null) {
                        gatt.close();
                        gatt = null;
                    }
                }

            }

            @Override
            public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {


                if (status == BluetoothGatt.GATT_SUCCESS) { gattInterface.onservicefound(gatt);}

Upvotes: 0

Views: 132

Answers (1)

MaliceInWonderland
MaliceInWonderland

Reputation: 81

I think Android does not actually disconnect the BLE link, but rather stops propagating BLE events to your application. This is just something I read once somehwere so take it with a grain of salt.

Upvotes: 1

Related Questions