在Kotlin Android应用程序中处理传入的蓝牙数据流 [英] Handling incoming bluetooth data stream in Kotlin Android app

查看:41
本文介绍了在Kotlin Android应用程序中处理传入的蓝牙数据流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个小应用程序,它通过蓝牙连接到一个附加了蓝牙盾牌的Arduino。我的蓝牙连接正常,我可以从我的应用程序向Arduino发送命令。我要在科特林做这件事。我是边走边学的,所以我误会了。这就是我希望有人能为我指路的地方。

您可以假设所有蓝牙连接设备都工作正常(的确如此)。

这是我的代码中处理向Arduino发送数据的部分。

private fun writeDataSendToMothership(outputToBt: String) {
    try {
        bluetoothSocket.outputStream.write(outputToBt.toByteArray())
        Log.i(LOGTAG, "Button clicked, info sent: $outputToBt")
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

button_led_on.setOnClickListener { writeDataSendToMothership("1")}
button_led_off.setOnClickListener { writeDataSendToMothership("0")}

我遇到麻烦的部分是从Arduino(母船)接收数据并对其进行处理。我想不出我需要做什么。

我想要做的是在应用程序中显示一个图像,这取决于Arduino在按下Arduino上的按钮后发送的内容。

到目前为止,我得到的是:

private fun readDataFromMothership(inputFromBt: String) {
    try {
        bluetoothSocket.inputStream.read(inputFromBt.toByteArray())
        Log.i(LOGTAG, "Incoming data from Mothership recieved: $inputFromBt")
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

private fun View.showOrInvisible(imageShow: Boolean) {
    visibility = if (imageShow) {
        View.VISIBLE
    } else {
        View.INVISIBLE
    }
}

这就是我失败的地方。

if (readDataFromMothership()) {
        imageView_mothership_button_pushed.showOrInvisible(true)
    } else {
        imageView_mothership_button_pushed.showOrInvisible(false)
    }

我遗漏了该函数调用中的任何内容。我尝试了许多不同的方法,但我只是不明白我需要什么参数,或者我离得太远了。我来对社区了吗?

编辑除了我缺乏编程常识外,我认为我的挂断与如何处理"inputFromBt"字符串有关。我需要使用某种类型的缓冲区吗。我正在尽力/研究/研究我所能做的一切。但却在拖延时间。

推荐答案

以下是我已有的、目前在我的应用程序中工作的代码:

private fun readBlueToothDataFromMothership(bluetoothSocket: BluetoothSocket) {
    Log.i(LOGTAG, Thread.currentThread().name)
    val bluetoothSocketInputStream = 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)
            liveData.postValue(readMessage)
        } catch (e: IOException) {
            e.printStackTrace()
            break
        }
    }
}

// display or don't star image
private fun View.showOrHideImage(imageShow: Boolean) {
    visibility = if (imageShow) View.VISIBLE else View.GONE
}

我在给用户frnnd的评论中提到,我的主要问题是我的Arduino发送的数据。我使用的是println()而不是print(),换行符把事情搞砸了。

这篇关于在Kotlin Android应用程序中处理传入的蓝牙数据流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆