Kotlin:将蓝牙数据传递给另一个活动
我正在制作一个 Android 应用程序,用于监控 Arduino Mega 2560 的传感器并使用蓝牙 HC-05 模块 连接应用程序和 Arduino。现在我已经完成蓝牙连接和写入,但我卡在读取上,我尝试在另一个活动中调用 readBluetoothData 但它冻结了活动并崩溃,我想知道如何将“readMessage”传递给另一个活动,以便我可以显示传感器值并阻止其崩溃。真的很想询问这方面的建议,因为我对 kotlin 和蓝牙编码都比较陌生。
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
}
}
}
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
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以使用楼上的应用程序类然后活动
类MainApp:Application(){
你的蓝牙连接对象
}
显现:
<应用
android:name=".MainApp"
在您的活动中
context?.applicationContext as MainApp).(您的蓝牙连接对象)
或使用单个活动应用程序和片段
can use aplication class it is upstairs then activity
class MainApp: Application() {
you bluetooth conection object
}
manifest:
<application
android:name=".MainApp"
in you activity
context?.applicationContext as MainApp).(you bluetooth conection object)
or use single activity app and fragments
我认为更好的解决方案是使用 Android 服务进行蓝牙工作,并使用广播接收器或类似的东西与应用程序交换数据
不要忘记使用另一个线程或进程来防止应用程序陷入循环
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