9

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
user1496230
  • 91
  • 1
  • 1
  • 2

4 Answers4

7

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.

Caner
  • 57,267
  • 35
  • 174
  • 180
Martze
  • 921
  • 13
  • 32
1

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

Sourav
  • 312
  • 1
  • 8
0

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

Rick Barrette
  • 272
  • 4
  • 19
0

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();
}