Kotlin:将蓝牙数据传递给另一个活动

发布于 2025-01-14 19:31:04 字数 718 浏览 4 评论 0原文

我正在制作一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

澉约 2025-01-21 19:31:04

可以使用楼上的应用程序类然后活动

类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

没有心的人 2025-01-21 19:31:04

我认为更好的解决方案是使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文