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!
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