Android - 启动蓝牙套接字 - 连接超时
Android - Initiate Bluetooth Socket - connection timeout
我需要连接到充当服务器的蓝牙设备。我知道它的 UUID(至少设备的文档包含它)。但是,当我尝试连接到它时出现异常。发现部分成功进行。
下面我引用了相关的代码部分
这是发现。成功找到我的设备后,我尝试连接它。
private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
private val bluetoothReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String = intent.action
when (action) {
BluetoothDevice.ACTION_FOUND -> {
val foundDevice: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
Log.i("NAME", foundDevice.name)
if (foundDevice.name.startsWith("RN487")) {
bluetoothAdapter?.cancelDiscovery()
device = foundDevice
val connectThread = ConnectThread(device)
connectThread.start()
}
}
}
}
}
private lateinit var device: BluetoothDevice
ConnectThread class 在这里:
private inner class ConnectThread(device: BluetoothDevice) : Thread() {
private val mSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
device.createRfcommSocketToServiceRecord(UUID)
}
override fun run() {
bluetoothAdapter?.cancelDiscovery()
mSocket?.use { socket ->
socket.connect()
toast("Connected!")
}
}
fun cancel() {
try {
mSocket?.close()
} catch (e: IOException) {
Log.e(TAG, "Could not close the client socket", e)
}
}
}
UUID 被指定为
private val UUID = nameUUIDFromBytes("49535343-...".toByteArray())
感谢您的宝贵时间和专业知识!
正如我一位眼尖的同事指出的那样,蓝牙描述以 "oldschool" version on the official android developers site. Later, the bluetooth low energy 开头,我的项目需要它。
我需要连接到充当服务器的蓝牙设备。我知道它的 UUID(至少设备的文档包含它)。但是,当我尝试连接到它时出现异常。发现部分成功进行。
下面我引用了相关的代码部分
这是发现。成功找到我的设备后,我尝试连接它。
private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
private val bluetoothReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val action: String = intent.action
when (action) {
BluetoothDevice.ACTION_FOUND -> {
val foundDevice: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
Log.i("NAME", foundDevice.name)
if (foundDevice.name.startsWith("RN487")) {
bluetoothAdapter?.cancelDiscovery()
device = foundDevice
val connectThread = ConnectThread(device)
connectThread.start()
}
}
}
}
}
private lateinit var device: BluetoothDevice
ConnectThread class 在这里:
private inner class ConnectThread(device: BluetoothDevice) : Thread() {
private val mSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
device.createRfcommSocketToServiceRecord(UUID)
}
override fun run() {
bluetoothAdapter?.cancelDiscovery()
mSocket?.use { socket ->
socket.connect()
toast("Connected!")
}
}
fun cancel() {
try {
mSocket?.close()
} catch (e: IOException) {
Log.e(TAG, "Could not close the client socket", e)
}
}
}
UUID 被指定为
private val UUID = nameUUIDFromBytes("49535343-...".toByteArray())
感谢您的宝贵时间和专业知识!
正如我一位眼尖的同事指出的那样,蓝牙描述以 "oldschool" version on the official android developers site. Later, the bluetooth low energy 开头,我的项目需要它。