Search code examples
androidsocketsbluetoothserversocket

Bluetooth creating socket error


I try to create BluetoothServerSocket on Samsung Galaxy Gio.

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothServerSocket tmp = null;
        try
        {
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_INSECURE, MY_UUID_INSECURE);
        }
        catch (IOException e)
        {
        }
        mmServerSocket = tmp;

When I no longer need to use a socket I just close it.

    public void cancel()
    {
        try
        {
            mmServerSocket.close();
        }
        catch (IOException e)
        {
        }
    }

In both cases no exceptions are throws. So my problem is. When i try to use 1st pease of code again( without exit from app) Log cat show me exception :

07-07 18:27:44.239: D/BluetoothSocket(13672): create BluetoothSocket: type = 1, fd =-1,
uuid = [null], port = 25
07-07 18:27:44.339: E/BLZ20_WRAPPER(13672): ##### ERROR : __listen_prot_rfcomm: failed       
with reason 1#####

That happens till then i don't reboot my phone or TurnOFF\wait\TurnOn my bluetooth. So i think the problem is that BluetoothServerSocket create sockets but he don't close it. Maybe my preconceptions is not right so i want to help.


Solution

  • After a bit of searching, I found this thread whose poster appears to get the same exception (Although it's in Italian, so I don't really understand...). If you scroll down a little, you'll see a java exception thrown for this native exception (__listen_prot_rfcomm: failed with reason 1). The java exception is java.io.IOException: Bad file number.

    You can find this problem in many threads online (Android Bluetooth IOException bad file number, Bluetooth failed to get port number). From these 2 we can learn that this problem is device specific. Some devices seem to keep the file descriptor of the socket alive, even after you close it with BluetoothServerSocket.close(), so you can't recreate any sockets using the same settings.

    The solution will depend on your application audience:

    • If you are not planning to publish it in the Play Store/Any other market, you could call BluetoothAdapter.disable(), and then re-enable it. This is very bad user experience, as an application shouldn't disable the bluetooth without asking the users first. But it will solve your problem, because all bluetooth file descriptors will be disposed automatically. So if the only user is you, it's a possible solution.
    • If you do plan on publishing this, you should find a real solution... It might not be easy, but this is indeed a major problem and it also seems that many devices are affected by it, so you can't publish your app as long as this problem persists.