broody
broody

Reputation: 707

Android Bluetooth IOException bad file number

I have a receive thread listening with the BluetoothServerSocket accept() call. This thread will be killed and restarted by another thread pretty frequently. When it gets the kill signal, it closes the BluetoothServerSocket therefore causing an IOException in accept(), and gets out of the infinite-loop. But occasionally, during these starts and restarts the listenUsingRfcommWithServiceRecord() call will catch a "bad file number" IOException and exit the loop prematurely. I think I may not be shutting down the BT component correctly in kill(?) but haven't figure out anything yet... Could someone give me some pointers?

private class ReceiveThread extends Thread {
    private final static String TAG = "ReceiveThread";
    private BluetoothServerSocket mmBtServer;
    private BluetoothSocket mmBtSocket;

    public ReceiveThread() {
        setName(TAG);
    }

    public void run() {
        if(D) Log.d(TAG,"RceiveThread running");

        while(true) {
            try {
                SetState(SERVICE_STATE.LISTENING);
                mmBtServer = mBtAdapter.listenUsingRfcommWithServiceRecord(mAppName, mUUID);

                if(D) Log.d(TAG,"ReceiveThd accepting connection");
                mmBtSocket = mmBtServer.accept();
                // Close server once socket establishes
                mmBtServer.close();

                if(D) Log.d(TAG, "Connection Established");
                SetState(SERVICE_STATE.CONNECTED_BUSY);



                /** Handle Processing **/



                // Close socket
                mmBtSocket.close();
            } catch (IOException e) {
                SetState(SERVICE_STATE.NOT_CONNECTED);
                Log.d(TAG,"IOException in ReceiveThread", e);
                break;
            }

            SetState(SERVICE_STATE.CONNECTED_IDLE);
        }
    }

    public void kill() {
        try {
            if(mmBtSocket!=null) mmBtSocket.close();
            if(mmBtServer!=null) mmBtServer.close();
        } catch (IOException e) {
            Log.d(TAG,"Failure killing ReceiveThread", e);
        }
        SetState(SERVICE_STATE.NOT_CONNECTED);
    }
}

Upvotes: 2

Views: 2013

Answers (1)

broody
broody

Reputation: 707

If anyone's interested.. I've found that this happens only on certain phones. I can consistently reproduce this on my Samsung Galaxy S after about 20-30 cycles of stops and starts. Quite frequently, I will also catch a "out of memory" from bluez which leads me to the problem resides beneath the api... I cannot reproduce this on Droid X, HTC G2, or myTouch 4G.

Upvotes: 2

Related Questions