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.

4
  • 3
    use AsyncTask Commented Jul 2, 2012 at 13:58
  • Do you actually have something that needs to be displayed on the screen? If not use a Service. If so use AsyncTask as @AdilSoomro says.
    – FoamyGuy
    Commented Jul 2, 2012 at 13:59
  • Another good (yet lengthy) resource would be developer.android.com/guide/components/…
    – gobernador
    Commented Jul 2, 2012 at 14:00
  • Create the Service that uses Timer and TimerTask. Commented Jul 2, 2012 at 14:03

4 Answers 4

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.

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

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.