Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run an infinite loop in Android without freezing the UI?

Tags:

android

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.

like image 208
user1496230 Avatar asked Jul 02 '12 13:07

user1496230


People also ask

How do you make a for loop run forever?

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.

How do you get out of an infinite loop?

You can press Ctrl + C .

Why does my loop go to infinite?

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.


2 Answers

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.

like image 87
Martze Avatar answered Oct 25 '22 20:10

Martze


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

like image 32
Sourav Avatar answered Oct 25 '22 20:10

Sourav