本文介绍了BluetoothSocket-连接超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以设置对BluetoothSocket的连接超时?

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

如果我的设备离线,则连接过程将花费几秒钟,然后返回错误.我需要将超时设置为1秒.有可能吗?

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类具有PROXY_CONNECTION_TIMEOUT,但从未使用过...感谢您的回答.

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

顺便说一句:

我尝试这样:

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

推荐答案

您无法更改BluetoothSocket.connect()的超时.作为文档:

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.

例如:超时5秒.使用CountDownTimer检查连接是否完成(成功或失败). 5秒后,如果连接不完整,请使用BluetoothSocket.close()取消.

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.

作为BluetoothSocket文档:

As BluetoothSocket documentation:

close()可用于中止另一个线程的调用.

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

这篇关于BluetoothSocket-连接超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 08:32