Skip to content

Instantly share code, notes, and snippets.

@Xiryl
Created August 12, 2021 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xiryl/dacfca2ecd0d6956d7d0c7d330f98dca to your computer and use it in GitHub Desktop.
Save Xiryl/dacfca2ecd0d6956d7d0c7d330f98dca to your computer and use it in GitHub Desktop.
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