简体   繁体   中英

Java Bluetooth Socket Wont Accept Connection after Restart

I've been scratching my head on this one all day. I have a Bluetooth socket that listens for devices. This is done with AsyncTask. The first time I try to connect to it from a remote device, I don't have any problems. Now I'm trying to simulate a disconnect. Either by going out of range, shutting off the remote device's Bluetooth adapter, or just remotely closing the connection. Right now the server socket throws an IOException when the connection is lost. I'm using this as my cue to restart the AsyncTask and start listening again. This appears to work fine, all my logcat messages are showing up on the restart so I know the task is running, but the socket wont accept a connection. Thinking this could be a problem with restarting the AsyncTask, I tried just dumping the connection right after its accepted. After resetting them, I still have the same issue, even if I call system.gc().

Heres some code I'm using now to test:

boolean running = true;
        while(running){
            btAdapter = BluetoothAdapter.getDefaultAdapter();
            btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord(NAME, ID);
            btSocket = btServerSocket.accept();

            btServerSocket.close();
            btSocket.close();

            btServerSocket = null;
            btSocket = null;
            btAdapter = null;

            System.gc();
            sleep(10);
        }

I really dont know what I'm doing wrong. Any help is greatly appreciated.

Thanks.

If you are only seeing this problem on Android 2.3.x, you might be running into a problem I just wrote about on another question. That problem also manifests as accept() working the first time, but then fails on successive tries. See my post here for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM