BluetoothSocket - connection timeout

青春壹個敷衍的年華 提交于 2020-01-17 07:30:12

问题


It's there any way to set connection timeout to BluetoothSocket?

If my device is offline, connection process takes a few seconds and then returns an error. I need to set the timeout to 1 second. It is possible?

BluetoothSocket socket = device.createRfcommSocketToServiceRecord(APP_UUID);
// socket.setProxyConnectionTimeout(1000); <- some like this
socket.connect();

BluetoothSocket class have PROXY_CONNECTION_TIMEOUT, but never used... Thanks for answers.

BTW:

I try some like this:

socket.connect();
Thread.sleep(1000);
socket.close(); // but socket is not closed & still connecting

回答1:


You can't change timeout of BluetoothSocket.connect(). As documentation:

This method will block until a connection is made or the connection fails. If this method returns without an exception then this socket is now connected. A workaround.

Ex: timeout 5s. Using CountDownTimer to check if connect is complete(success or fail). After 5s, if connection is incomplete then use BluetoothSocket.close() to cancel.

As BluetoothSocket documentation:

close() can be used to abort this call from another thread.




回答2:


Ok this code is only slightly tested but it works so far:

Task.Run(() =>
    {
        while (true)
        {
            socket = pairedBTDevice.CreateRfcommSocketToServiceRecord(UUID.FromString(uuid));
            socket.ConnectAsync();
            Thread.Sleep(1000);
            if (socket.IsConnected)
            {
                // call a function here
                // my function blocks for the application lifetime
                return;
            }
            else
            {
                socket.Close();
            }
        }

    });

I hope this helps.



来源:https://stackoverflow.com/questions/42579345/bluetoothsocket-connection-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!