Home > OS >  Kotlin: Read bluetooth data real time
Kotlin: Read bluetooth data real time

Time:09-16

So I'm fairly new to Kotlin and Bluetooth, I am making and Android app to read the data from my Arduino sensors in real time so that track of the current readings of each sensor. Right now my read works and I have tried using Handler to keep reading but my problem is that when it keeps reading it also lags the application, it doesn't crash or anything and reads fine, but inputting texts and going to other activities takes a while, so I can confidently say that it must be my Handler that's lagging the application. So my question, is there a better way of making handler not lag my app but still read the sensors? Or is there other ways that I can use other than Handler?

companion object {
        var m_myUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
        var m_bluetoothSocket: BluetoothSocket? = null
        lateinit var m_progress: ProgressDialog
        lateinit var m_bluetoothAdapater: BluetoothAdapter
        var m_isConnected: Boolean = false
        lateinit var  m_address: String
        private val mmBuffer: ByteArray = ByteArray(1024)
        private const val TAG = "MY_APP_DEBUG_TAG"
        var  buffer = ByteArray (1024)
        var bytes: Int = 0
        lateinit var arrVal: Array<String>
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.control_layout)
        m_address = intent.getStringExtra(BluetoothActivity.EXTRA_ADDRESS)!!
        ConnectToDevice(this).execute()

        val handler = Handler()
        val runnable = object : Runnable{
            override fun run() {
                readSensors()
                handler.postDelayed(this, 2000)
            }
        }

        Handler().postDelayed({
            Log.e("Thread", runnable.run().toString())
            val intent = Intent(this, MainActivity::class.java)
            finish()
            startActivity(intent)
        }, 5000)
    }

Here is oncreate() where I have placed the Handler runnable and companion object arrVal so I can just use the variable in other activities to display the data.

private fun readSensors() {
        val bluetoothSocketInputStream = m_bluetoothSocket!!.inputStream
        val delim = ","
        var readMessage: String = ""
        //Loop to listen for received bluetooth messages
        while (!(readMessage.contains('*'))) {
            try {
                bytes = bluetoothSocketInputStream.read(buffer)
                readMessage = String(buffer, 0, bytes)

                arrVal =  readMessage.split(delim).toTypedArray()

            } catch (e: IOException) {
                e.printStackTrace()
                break
            }
        }
    }

Here is my function for reading the sensors.

CodePudding user response:

Handler is not a Thread. See handler constructor source code, it is attached to Looper of the current thread. So your code in Runnable is posted to message queue of main thread and executed from there.

To prevent main thread from freezing, you have to do all IO and CPU consuming operations on separate threads.

  • Java high level API to do this is called Executors.
  • Kotlin way is Coroutines.

You can archive expected behaviour with Handler API (by creating a thread with looper and using Handler to post messages to that thread) but don't waste your time on this.

  • Related