我有一个简单的应用程序,可通过rfcomm协议与蓝牙服务器通信。有时我可以建立良好的连接,但经常我启动应用程序并收到以下错误。我不知道从什么原因开始寻找问题的原因,因为正如我所说,它实际上有时会起作用。
Logcat:
D/CONNECTTHREAD: Could not connect: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@351854e, channel: 6, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@8a7b66f, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@1d8af7cmSocket: android.net.LocalSocket@4a2b005 impl:android.net.LocalSocketImpl@3c4a85a fd:java.io.FileDescriptor@5a34a8b, mSocketState: INIT
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@351854e, channel: 6, mSocketIS: android.net.LocalSocketImpl$SocketInputStream@8a7b66f, mSocketOS: android.net.LocalSocketImpl$SocketOutputStream@1d8af7cmSocket: null, mSocketState: CLOSED
这是我用来连接的方法:
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import android.util.Log
import java.io.IOException
import java.util.*
class ConnectThread(private val bTDevice: BluetoothDevice, uuid: UUID) : Thread() {
private val bTSocket: BluetoothSocket?
init {
var tmp: BluetoothSocket? = null
try {
tmp = this.bTDevice.createRfcommSocketToServiceRecord(uuid)
} catch (e: IOException) {
Log.d("CONNECTTHREAD", "Could not start listening for RFCOMM")
}
bTSocket = tmp
}
// Get Bluetooth socket
fun getSocket(uuid: UUID?): BluetoothSocket? {
val bTSocket: BluetoothSocket?
var tmp: BluetoothSocket? = null
try {
tmp = this.bTDevice.createRfcommSocketToServiceRecord(uuid)
} catch (e: IOException) {
Log.d("CONNECTTHREAD", "Could not start listening for RFCOMM")
}
bTSocket = tmp
return bTSocket
}
// Connect to device
fun connect(bTSocket: BluetoothSocket?): Boolean {
try {
bTSocket!!.connect()
if (bTSocket.isConnected) {
// deviceItem.connected = true
Log.d("CONNECTTHREAD", "Connected")
}
} catch (e: IOException) {
Log.d("CONNECTTHREAD", "Could not connect: " + e.toString())
try {
bTSocket!!.close()
} catch (close: IOException) {
Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString())
}
return false
}
return true
}
// Cancel connection
fun cancel(bTSocket: BluetoothSocket?): Boolean {
try {
bTSocket!!.close()
if (!bTSocket.isConnected) {
Log.d("CONNECTTHREAD", "Connection cancelled")
}
} catch (e: IOException) {
return false
}
return true
}
}