1

In my Android app, I have a snippet of code, similar to Run code for x seconds in Java?

long t= System.currentTimeMillis();
long end = t+15000;
while(System.currentTimeMillis() < end) {
//useful calculation
}

And this code will freeze the UI thread, so I'm wondering if there's a way to continuously pass in data to my AsyncTask that will do the calculation in the background thread to avoid freezing? Or is there a better way, or to keep calling AsyncTask from within my while loop?

Community
  • 1
  • 1
Jasmine Rain
  • 419
  • 2
  • 6
  • 17
  • Sounds like you want a Thread rather than an AsyncTask. If something should continually process in the background, a Thread is a better fit. AsyncTasks by default operate all on a single thread, so you shouldn't use one to do more than a few seconds worth of processing. Beyond that- what kind of data do you want to pass it, with what frequency? A normal way of doing this would be via a synchronized messaging queue. Passing data to a thread or task is possible, but easy to do wrong. – Gabe Sechan Feb 27 '16 at 23:57
  • Look into the Handler or Service classes in Android. – OneCricketeer Feb 28 '16 at 00:09
  • @GabeSechan I'm reading data (double) from a sensor, not a sensor on the phone, at very high frequency (at least to the eye), I'm not sure what, but it looks like 10Hz ish. Can you point me to a document or something? – Jasmine Rain Feb 28 '16 at 00:24
  • A synchronized message queue with the sensor handler writing data to the queue and the thread reading (or waiting for data to be available) sounds about right to me. – Gabe Sechan Feb 28 '16 at 00:26

1 Answers1

0

For this purpose, use a Handler instead.

It goes like this :

Handler timerHandler = new Handler();

Runnable timerRunnable = new Runnable() {

    @Override
    public void run() {
        //READ HERE WHAT YOU NEED FROM THE SENSOR (useful calculation)

        //And then set the next execution of the sensor reading
        timerHandler.postDelayed(this, 1000); //runs 1000 milliseconds
    }
};

//Launch It for the first time
timerHandler.post(timerRunnable);

//Whenever you would like to stop it, use the following commented line
//timerHandler.removeCallbacks(timerRunnable);
user3793589
  • 418
  • 3
  • 14