android bluetooth connection fails after 489 successful connections

后端 未结 4 1025
一整个雨季
一整个雨季 2021-01-02 07:54

unfortunately, I have some problems with android\'s bluetooth. For my test environment I use a Nexus 4 with Android 4.4.2.

I have a Java Application on my PC, which

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-02 08:18

    The problem seems connected to the limit of file descriptors on your device. There is a report for that issue here

    During the creation of a Bluetooth socket a new fd is two new FDs are acquired from the system. It seems you are not closing your previous BT connections correctly so the number of used FDs steadily increases until you hit the limit.

    To avoid this you will at least have to call close() on the BluetoothServerSocket you receive from the listenUsingRfcommWithServiceRecord() call after finishing the operations for it. You should also check if you are holding on to other resources connected to the BT connection and free them if possible.


    As it was requested here is how to force the closing of the ParcelFileDescriptor of the BluetoothServerSocket. Beware: it may break things!

    You will have to access the mSocket field of the BluetoothServerSocket to access the underlying BluetoothSocket. This BluetoothSocket holds the ParcelFileDescriptor in the field mPfd. And on that you can call close(). As both fields are not visible you will have to use Reflections:

    public void closePFD(BluetoothServerSocket closeMe) throws AllKindOfExceptionsThatYouHaveToHandle
    {
        Field mSocketFld = closeMe.getClass().getDeclaredField("mSocket");
        mSocketFld.setAccessible(true);
    
        BluetoothSocket btsock = (BluetoothSocket)mSocketFld.get(closeMe);
    
        Field mPfdFld = btsock.getClass().getDeclaredField("mPfd");
        mPfdFld.setAccessible(true);
    
        ParcelFileDescriptor pfd = (ParcelFileDescriptor)mPfdFld.get(btsock);
    
        pfd.close();
    }
    

    This will close the BluetoothServerSocket. If you want to close just the BluetoothSocket from the BTServerSockets accept method you can leave out the part of getting mSocket as seen in jitain sharmas answer.

提交回复
热议问题