feat: add listening and sending data to bt service
This commit is contained in:
parent
a74d0ddef5
commit
4f40490fee
@ -11,7 +11,6 @@ import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.core.content.ContextCompat.getSystemService
|
||||
import com.example.tvcontroller.data.BluetoothDevice
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
@ -120,6 +119,7 @@ class BluetoothService(private val context: Context) {
|
||||
currentDevice = device
|
||||
state = STATE_CONNECTED
|
||||
Log.i(TAG, "Connected to device: $device")
|
||||
listenForIncomingData()
|
||||
} catch (e: IOException) {
|
||||
state = STATE_DISCONNECTED
|
||||
Log.e(TAG, "Error connecting to device: $e")
|
||||
@ -139,6 +139,35 @@ class BluetoothService(private val context: Context) {
|
||||
state = STATE_DISCONNECTED
|
||||
}
|
||||
|
||||
private fun listenForIncomingData() {
|
||||
if (clientSocket == null || !clientSocket!!.isConnected) return
|
||||
Log.i(TAG, "Listening for incoming data")
|
||||
val buffer = ByteArray(1024)
|
||||
while (true) {
|
||||
try {
|
||||
val bytesRead = clientSocket?.inputStream?.read(buffer)
|
||||
if (bytesRead != null && bytesRead != -1) {
|
||||
val data = buffer.decodeToString(endIndex = bytesRead)
|
||||
Log.i(TAG, "Received data: $data")
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "Error reading from socket: $e")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun sendData(data: String) {
|
||||
if (clientSocket == null || !clientSocket!!.isConnected) return
|
||||
try {
|
||||
val bytes = data.encodeToByteArray()
|
||||
clientSocket?.outputStream?.write(bytes)
|
||||
Log.i(TAG, "Sent data: $data")
|
||||
} catch (e: IOException) {
|
||||
Log.e(TAG, "Error writing to socket: $e")
|
||||
closeBluetoothConnection()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val STATE_OFF = "off"
|
||||
const val STATE_DISCONNECTED = "disconnected"
|
||||
|
||||
Loading…
Reference in New Issue
Block a user