4

I need to read data constantly from USB (50ms interval at least) and update several View's at the same time.

Updating View's can be quite easily achieved by using a Handler, but since USB reading performs too much work and there's no need to touch the UI Thread, it has to be done on a different thread.

I have read a few questions like this about executing AsyncTask repeatedly but please correct me if I'm wrong: it seems it's not a good way to go.

What are the best ways to execute background work repeatedly in Android?

Community
  • 1
  • 1
Machado
  • 14,105
  • 13
  • 56
  • 97

1 Answers1

4

If you need some finer grained control on the time elapsed, I suggest you start a separate thread with a loop, and use Thread.sleep to wait before polling. When you have something new, dispatch it with the Handler to the UI thread.

Something like this (rough sketch, should give you an idea):

    new Thread() {
        private boolean stop = false;

        @Override public void run() {
            while (!stop) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // poll the USB and dispatch changes to the views with a Handler
            }
        }

        public void doStop() {
            stop = true;
        }
    };
Machado
  • 14,105
  • 13
  • 56
  • 97
Sebastian
  • 1,076
  • 9
  • 24