'Kotlin: Pass Bluetooth data to another Activity
I am making an android app that monitors sensors from my Arduino Mega 2560 and using Bluetooth HC-05 Module to connect the app and the Arduino. Right now I have the bluetooth connection and write done but I am stuck on read, I tried calling readBluetoothData in another activity but it freezes the activity and crashes, I would like to know how to pass "readMessage" to another Activity so I can display the sensor values and to stop it from crashing. Really would like to ask advice on this since I am relatively new to both kotlin and Bluetooth coding.
private fun readBluetoothData() {
val bluetoothSocketInputStream = m_bluetoothSocket!!.inputStream
val buffer = ByteArray(1024)
var bytes: Int
//Loop to listen for received bluetooth messages
while (true) {
try {
bytes = bluetoothSocketInputStream.read(buffer)
val readMessage = String(buffer, 0, bytes)
} catch (e: IOException) {
e.printStackTrace()
break
}
}
}
Solution 1:[1]
I think the better solution is using Android service for bluetooth work and exchange data with app using broadcast receiver or something similar Don't forget to use another thread or process for preventing app to stuck in a loop
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sergey Malkov |
