I'm creating and android program which needs to to continuously keep sending data over the bluetooth now I use something like this:
for(;;)
{
//send message
}
though this works it freezes my UI and app how can I implement the same without freezing my UI?
I am sure that the app is sending the data as I monitor the data.
To make an infinite loop, just use true as your condition. true is always true, so the loop will repeat forever. Warning: Please make sure you have a check that exits your loop, otherwise it will never end.
You can press Ctrl + C .
Most of the times, it's because the variables used in the condition are not being updated correctly, or because the looping condition is in error.
Put your loop in an AsyncTask
, Service
with separate Thread or just in another Thread beside your Activity. Never do heavy work, infinte loops, or blocking calls in your main (UI) Thread.
If you are using kotlin then you can use coroutines.
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4"
initialize a job variable job:Job
globally
then do:
job =
GlobalScope.launch(Dispatchers.Default) {
while (job.isActive) {
//do whatever you want
}
}
Do job.cancel()
when you want your loop to stop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With