-1

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
        }
    }
}
gre_gor
  • 6,669
  • 9
  • 47
  • 52
Xenon
  • 1
  • Could you also put the crash log? Have you tried to call your method using coroutines and Dispatcher.IO? https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html – TabascoLosco Mar 17 '22 at 09:43
  • https://imgur.com/sAW1t8m here is my logs. I haven't tried coroutines yet, since I haven't seen any references on it or tutorials. – Xenon Mar 17 '22 at 10:30

2 Answers2

0

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

  • Your post might benefit from using this info https://stackoverflow.com/editing-help Currently it is so hard to read that for some seconds there I thought you are asking for help instead of trying to answer. Also please take the [tour] and read [answer]. – Yunnosch Jan 24 '23 at 10:25
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 25 '23 at 05:05
-1

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

  • 1
    Hi Sergey and welcome to StackOverflow. In order to provide helpful answers, please have a look at how to write a good answer (https://stackoverflow.com/help/how-to-answer). Specifically, you might want to provide a MWE (https://stackoverflow.com/help/minimal-reproducible-example). – MathMax Mar 17 '22 at 13:19