Android-реализованный код подключения Bluetooth, но не работает на другом устройстве AndroidAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Android-реализованный код подключения Bluetooth, но не работает на другом устройстве Android

Сообщение Anonymous »

Я работаю над приложением Android, которое подключается к устройству Bluetooth с помощью BluetoothSocket. Однако, когда я пытаюсь подключиться, я получаю следующую ошибку:
работает, когда я пытаюсь подключиться к Bluetooth от ноутбука, но сбой, когда попробуйте подключиться с другим устройством Android (Redmi A2 (Androdi OS 13)) < /p >
Attempting to connect... Attempt 3
connect() for device XX:XX:XX:XX:69:7D called by pid: 5069
read failed, socket might be closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:1079)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:588)
at com.sample.BluetoothUtil$ConnectThread.run(BluetoothUtil.kt:156)
< /code>
Текущая реализация < /p>
Вот подключение, которое я использую для установления соединения Bluetooth: < /p>
private inner class ConnectThread(val device: BluetoothDevice?) : Thread() {
private val connectionUUID = device?.getUuids()?.get(0)?.getUuid()
private var bluetoothSocket: BluetoothSocket? = null

override fun run() {
dataObjects.bluetoothAdapter?.cancelDiscovery()

bluetoothSocket = device?.createInsecureRfcommSocketToServiceRecord(connectionUUID)
bluetoothSocket?.let { socket ->
try {
val maxRetries = 3
var attemptCount = 0

while (!connectionAttempted && attemptCount < maxRetries) {
try {
Log.d("BLUETOOTH_CONNECT", "Attempting to connect... Attempt ${attemptCount + 1}")
isConnecting = true

// Wait for bonding to complete if in progress
while (device?.bondState == BluetoothDevice.BOND_BONDING) {
Thread.sleep(100)
}

socket.connect()
connectionAttempted = true
Log.d("BLUETOOTH_CONNECT", "Connection successful")
showToast("Connected to ${device?.name ?: "device"}")
return
} catch (e: IOException) {
Log.e("BLUETOOTH_CONNECT", "Connection attempt failed", e)
attemptCount++
isConnecting = false
if (attemptCount < maxRetries) {
Thread.sleep(1000)
}
}
}

if (!connectionAttempted) {
Log.e("BLUETOOTH_CONNECT", "Failed to connect after $maxRetries attempts")
showToast("Failed to connect after several attempts")
cancel()
}
} catch (e: Exception) {
Log.e("BLUETOOTH_CONNECT", "Connection error", e)
showToast("Connection error: ${e.localizedMessage}")
isConnecting = false
cancel()
}
} ?: run {
Log.e("BLUETOOTH_CONNECT", "Socket is null")
showToast("Error: Could not create Bluetooth socket")
}
}

fun cancel() {
try {
isConnecting = false
connectionAttempted = false
bluetoothSocket?.close()
} catch (e: Exception) {
Log.e("BLUETOOTH_CONNECT", "Could not close socket", e)
}
}
}

fun connectToDevice(device: BluetoothDevice?) {
var connectThread: ConnectThread? = null
connectThread?.cancel()
connectThread = ConnectThread(device)
connectThread.start()
}


Подробнее здесь: https://stackoverflow.com/questions/794 ... her-androi
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»