user1496230
user1496230

Reputation: 91

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

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.

Upvotes: 9

Views: 13661

Answers (4)

Sourav
Sourav

Reputation: 402

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

Upvotes: 1

Start an IntentService which will create a background thread for you to run your Service in. Call Looper.prepare() as @YellowJK suggests, but then call Looper.loop() when you need your program to wait for something to happen so the Service isn't killed.

@Override
protected void onHandleIntent(Intent arg0) {
   Looper.prepare();
   //Do work here
   //Once work is done and you are waiting for something such as a Broadcast Receiver or GPS Listenr call Looper.loop() so Service is not killed
   Looper.loop();
}

Upvotes: 0

Martze
Martze

Reputation: 921

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.

Upvotes: 7

Rick Barrette
Rick Barrette

Reputation: 282

You need to move the work into another thread (other than the UI thread), to prevent ANR.

new Thread( new Runnable(){
        @Override
        public void run(){
            Looper.prepare();
            //do work here
        }
    }).start();

The above is a quick and dirty method, The preferred method in most cases is using AsyncTask

Upvotes: 0

Related Questions