Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
BluetoothSDK-Service3
private inner class ConnectedThread(private val mmSocket: BluetoothSocket) : Thread() {
private val mmInStream: InputStream = mmSocket.inputStream
private val mmOutStream: OutputStream = mmSocket.outputStream
private val mmBuffer: ByteArray = ByteArray(1024) // mmBuffer store for the stream
override fun run() {
var numBytes: Int // bytes returned from read()
// Keep listening to the InputStream until an exception occurs.
while (true) {
// Read from the InputStream.
numBytes = try {
mmInStream.read(mmBuffer)
} catch (e: IOException) {
pushBroadcastMessage(
BluetoothUtils.ACTION_CONNECTION_ERROR,
null,
"Input stream was disconnected"
)
break
}
val message = String(mmBuffer, 0, numBytes)
// Send to broadcast the message
pushBroadcastMessage(
BluetoothUtils.ACTION_MESSAGE_RECEIVED,
mmSocket.remoteDevice,
message
)
}
}
// Call this from the main activity to send data to the remote device.
fun write(bytes: ByteArray) {
try {
mmOutStream.write(bytes)
// Send to broadcast the message
pushBroadcastMessage(
BluetoothUtils.ACTION_MESSAGE_SENT,
mmSocket.remoteDevice,
null
)
} catch (e: IOException) {
pushBroadcastMessage(
BluetoothUtils.ACTION_CONNECTION_ERROR,
null,
"Error occurred when sending data"
)
return
}
}
// Call this method from the main activity to shut down the connection.
fun cancel() {
try {
mmSocket.close()
} catch (e: IOException) {
pushBroadcastMessage(
BluetoothUtils.ACTION_CONNECTION_ERROR,
null,
"Could not close the connect socket"
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment