android - 如何在kotlin中通过蓝牙接收字符串

标签 android kotlin

我需要创建一个函数,通过循环从缓冲区读取通过蓝牙接收的字符串,这是我到目前为止所做的,但它不起作用,如果我使用 while 循环它只会卡在循环中,也许我错过了正确的条件。

private suspend fun getmeData(){
        var bytes :Int
        val buffer: ByteArray = ByteArray(1024)
        var readMessage : String = ""
        if (m_isConnected ) {
            try {   

               while(){         
                   //read bytes received and ins to buffer
                   bytes =_bluetoothSocket!!.inputStream.read(buffer)
                   //convert to string
                   readMessage = readMessage + String(buffer, 0,bytes)
              }
            } catch (ex: Exception) {
                ex.printStackTrace()
                
            }
        } else {            
            val toast = Toast.makeText(
                contesto, "Non connesso",
                Toast.LENGTH_LONG
            )
            toast.show()
        }
    }

最佳答案

嗨,伙计们,在与一位同事进行有趣的对话后,我找到了解决方案,“try”代码中的 while 条件必须是这样的,因为我收到的字符串包含一个结束字符串符号

 while (!(readMessage.contains(';'))){
        /*my code*/
 }
感谢大家的努力! <3

关于android - 如何在kotlin中通过蓝牙接收字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64403968/

相关文章:

android - ProgressDialog 是否可绘制? GIF 什么的?

android - 如何修复 DefaultKotlinSourceSetKt 的初始化错误?

kotlin - 如何通过改造阻塞客户端和协程实现有限调用

android - 错误 :Binary XML file line : Inflating class fragment

android - flutter - UI 更改仅在点击另一个元素时生效

android SupportMapFragment 错误膨胀 fragment 类

android - 如何禁用 WebView 中的垂直和水平滚动?

hibernate - 无法在 Kotlin 中添加条件 api 谓词,获取类型接口(interface)失败错误

java - 如何从 Activity 外部扩展 SupportActionBar 菜单

java - 我无法在使用 android 中的 java 的 Retrofit2 调用中接收响应无法解析模型中的响应