• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Is this Android Kotlin socket request blocking even it is inside a Coroutine

penitko

Lurker
Jul 21, 2023
1
0
I want to do Android Apps that uses socket queries to microcontrollers and these Android Apps are not very difficult, just short stream Socket requests and respoinses . But I am a new comer, so at the beginnign I am asking : Is this Andfrid Kotlin socket request in a Activity blocking UI thead even it is inside a Coroutine?

Note: I had to put Kotlin class in a Java code tags because I didn't find Kotlin code tags!

Java:
class MainActivity : AppCompatActivity() {
    private var active : Boolean = false
    private var data : String = ""

    //private var button = Button(this)
    private lateinit var textView : TextView
    private lateinit var button : Button

    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button = findViewById(R.id.button)
        textView = findViewById(R.id.textView)

        val address = "192.168.0.100"
        val port = 5000

        button.setOnClickListener { it: View!
            if (button.text == "connect")
            {
                active = true
                CoroutineScope(IO).launch{ this: CoroutineScope
                    client(address, port)
                }

            }
            else
            {
                active = false
                button.text = "connect"
            }
        }//button

    }//onCreate

    final suspend fun client(address: String, port: Int){
        val connection = Socket(address, port)
        val writer : OutputStream = connection.getOutputStream()
        writer.write(1)
        val reader = Scanner(connection.getInputStream())
        while(active)
        {
            var input = ""
            input = reader.nextLine()

            if (data.length < 300)
                data += "\n$input"
            else
                data = input

            textView.text = data
        }//while
        reader.close()
        writer.close()
        connection.close()
    }

}//class
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones